Quick Tip: Spring REST Utility for Current HTTP Request
Join the DZone community and get the full member experience.
Join For FreeUtility Method for Spring REST
public static HttpServletRequest getCurrentRequest() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder"); Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes); HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest(); Assert.state(servletRequest != null, "Could not find current HttpServletRequest"); return servletRequest; }
Sometimes it’s easier to get the underlying Servlet request to get some headers or variables.
final String userIpAddress = getCurrentRequest().getRemoteAddr(); final String userAgent = getCurrentRequest().getHeader("user-agent");
This is used in the simple REST service using HTTP Post verb @ the awesome CloudFoundry:
REST
Web Protocols
Spring Framework
Published at DZone with permission of Tim Spann, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments