SpringBoot 设置response header

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值