Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify Http headers before executing request in spring boot mvc

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) 
        {
           ...
        }
    }
like image 618
pvjhs Avatar asked Oct 17 '22 17:10

pvjhs


1 Answers

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);
  }

}

like image 91
turong Avatar answered Oct 20 '22 17:10

turong