SpringBoot 设置response header(全局设置和单独controller设置)

目录

前言

单个请求响应设置

Using HttpServletResponse

Using ResponseEntity

全局响应Response设置

Adding a Header for All Responses


前言

应为项目需要设置安全请求头信息,防止一些安全攻击。找了全网基本无果,最后还是通过国外的一些文献,问题得以解决。

单个请求响应设置

如果我们要在单个请求响应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);
    }
}

参考文章:

https://www.baeldung.com/spring-response-header

猜你喜欢

转载自blog.csdn.net/qq_26878363/article/details/102487207