5

I have multiple rest endpoints. userId (http header) is common in all endpoints. I want to apply a logic, let say set its default value if not provided or trim it if is provided in request before request enters the method (for eg: heartbeat). How can we achieve this in spring boot rest mvc.

@RestController public class MyResource { @RequestMapping(value = "/heartbeat", method= RequestMethod.GET) public String heartbeat (@RequestHeader (value="userId", required=false) String userId) { ... } } 
1
  • 1
    You may use an interceptor Commented May 26, 2018 at 15:50

2 Answers 2

4

Can you try this?

@Configuration @Slf4j public class HttpHeaderModificationConfig implements Filter { private static final String HEADER_DEMO_NAME = "name"; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; // modify HTTP Request Header final HttpServletRequestWrapper reqWrapper = new HttpServletRequestWrapper(req) { @Override public String getHeader(String name) { if (HEADER_DEMO_NAME.equals(name)) { return "Changed"; } return super.getHeader(name); } }; log.info("After Changed with Name {}", reqWrapper.getHeader(HEADER_DEMO_NAME)); chain.doFilter(reqWrapper, response); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

I would add @Order(Ordered.HIGHEST_PRECEDENCE) if the modification should be before any logic
works very well
0

One option i can think of using Filters i.e. create a Filter to check for the header userId and trim it if its present or provide it a default value if its not present and store it in another header lets say customUserId. In your controller you can comfortably use your custom headers to be sure of that it will be valid as per your requirements. You can refer to the below article for creating a generic bean

https://www.baeldung.com/spring-boot-add-filter

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.