In Spring MVC, there are many ways to dynamically set request headers and response headers. Here are some common ways:
Set request header
Use @RequestHeader annotation
This annotation is used to read a single HTTP header value in the request and pass it as a parameter to the controller method.
@RequestMapping("/example") public String handleRequest(@RequestHeader(name = "X-Custom-Header", required = false) String customHeaderValue) { // Use customHeaderValue... return "viewName"; }
Using ControllerAdvice
Through the ControllerAdvice class, you can add response headers globally.
@ControllerAdvice public class GlobalHeaderControllerAdvice { @AfterResponseBodyAdvice public void addGlobalHeader(@RequestHeader HttpHeaders headers) { ("X-Global-Response-Header", "GlobalValue"); } }
Headers attribute annotated with @RequestMapping
For @RequestMapping and its derived annotations (such as @GetMapping, @PostMapping, etc.), the headers attribute can be used to specify the constraints of the request, which can be used to simulate the effect of the request header.
@RequestMapping(value = "/example", method = , headers = "X-Custom-Header=someValue") public String conditionalRequestMapping() { // Method implementation...}
Using HttpServletRequest
By injectionHttpServletRequest
Objects that can read and modify request headers (usually used for reading, because the HTTP request header is already set when the request reaches the servlet and cannot be modified).
@RequestMapping("/example") public String handleRequest(HttpServletRequest request) { String customValue = ("X-Custom-Header"); // Use customValue... return "viewName"; }
Using ClientHttpRequestInterceptor
accomplishClientHttpRequestInterceptor
Interface, you can dynamically add or modify the request header before the request is sent.
public class CustomRequestHeaderInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { ().set("X-Custom-Request-Header", "DynamicValue"); return (request, body); } }
Using Filter
Generally, the HTTP request header is set when the client sends a request, and once the request is sent to the server, the request header cannot be modified. Filter can read and modify the HttpServletRequest object, but it cannot modify the request header that has been received, because the HTTP protocol itself does not support modifying the request header.
If you need to "forge" or "add" the request header on the server side, this is usually achieved by setting properties in the Filter into the HttpServletRequest, but these properties will not become part of the HTTP request header, they can only be used by downstream Servlet or controller methods.
public class CustomRequestHeaderFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; ("X-Custom-Header", "HeaderValue"); (request, response); } }
Custom requests with RestTemplate
If you use it in the controllerRestTemplate
To initiate a request, you can set the value dynamically in the request header.
HttpHeaders headers = new HttpHeaders(); ("X-Custom-Request-Header", dynamicHeaderValue); HttpEntity<String> entity = new HttpEntity<>("Request Body", headers); (...);
Set the response header
Use @ResponseHeader annotation
Use on controller classes or methods@ResponseHeader
The annotation directly adds the response header.
@Controller @ResponseHeader("X-Custom-Response-Header: DynamicValue") public class ExampleController { // Controller method...}
Using HttpServletResponse
By injectionHttpServletResponse
Object, called in the controller methodsetHeader
oraddHeader
Method to set the response header.
@RequestMapping("/example") public String handleRequest(HttpServletResponse response) { ("X-Custom-Response-Header", "DynamicValue"); return "viewName"; }
Using ResponseEntity Object
Return oneResponseEntity
Object, allowing you to set status codes, headers, and response bodies.
@RequestMapping("/example") public ResponseEntity<String> handleRequest() { HttpHeaders headers = new HttpHeaders(); ("X-Custom-Response-Header", "DynamicValue"); return new ResponseEntity<>("Response Body", headers, ); }
Using HandlerInterceptor
accomplishHandlerInterceptor
Interface, you can dynamically add response headers after request processing.
public class CustomResponseHeaderInterceptor implements HandlerInterceptor { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { ("X-Custom-Response-Header", "DynamicValue"); } }
Using Filter
Create a filter that dynamically sets the response header after the request is processed.
public class CustomHeaderFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { (servletRequest, servletResponse); HttpServletResponse response = (HttpServletResponse) servletResponse; ("X-Custom-Response-Header", "DynamicValue"); } }
Responsive call using RestClient
If you use responsive programming, you can set the response header dynamically when calling an external service.
public Mono<ResponseEntity<String>> callExternalService(Data data) { return () .uri("/example") .header("X-Custom-Response-Header", dynamicHeaderValue) .retrieve() .bodyToMono(); }
illustrate
These methods can be flexibly used according to your specific needs and scenarios, such as whether you need to add headers at a specific stage of request processing, or whether you need to add headers globally.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.