单个请求响应设置
如果我们要在单个请求响应response增加header,可以使用httpServletResponse 或者 ResponseEntity objects.
Using HttpServletResponse
We simply have to add the HttpServletResponse object to our REST endpoint as an argument, then use the addHeader() method:
@GetMapping("/http-servlet-response")
public String usingHttpServletResponse(HttpServletResponse response) {
response.addHeader("Baeldung-Example-Header", "Value-HttpServletResponse");
return "Response with header using HttpServletResponse";
}
Using ResponseEntity
In this case, let's use the BodyBuilder provided by the ResponseEntity class:
@GetMapping("/response-entity-builder-with-http-headers")
public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header",
"Value-ResponseEntityBuilderWithHttpHeaders");
return ResponseEntity.ok()
.headers(responseHeaders)
.body("Response with header using ResponseEntity");
}
全局响应Response设置
另一方面,如果我们要在所有response增加header我们需要使用Filter
Adding a Header for All Responses
Now let's imagine we want to set a particular header to many of our endpoints.
Of course, it would be frustrating if we have to replicate the previous code on each mapping methods.
A better approach to accomplish this is by configuring a Filter in our service:
@Component
public class AddResponseHeaderFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.addHeader("X-Frame-Options", "DENY");
httpServletResponse.addHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
httpServletResponse.addHeader("Cache-Control", "no-cache='set-cookie'");
httpServletResponse.addHeader("Pragma", "no-cache");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}