Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip: Spring REST Utility for Current HTTP Request

DZone's Guide to

Quick Tip: Spring REST Utility for Current HTTP Request

· Integration Zone
Free Resource

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

Utility 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:

(Source)

Tool for Creating Your Test JSON.

Spring Boot Documentation

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:

Published at DZone with permission of Tim Spann, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}