Java OpenResty Spring Spring Boot MySQL Redis MongoDB PostgreSQL Linux Android Nginx 面试 小程序 Arthas JVM AQS juc Kubernetes Docker 诊断工具


Spring Boot 统一添加响应头的几种方式

Spring Boot 大约 2244 字

HttpServletResponse 方式

@RestController
public class HelloController {   

    @GetMapping("/hello")
    public String viewController(HttpServletResponse response){
        response.setHeader("header name", "header value");
        return "hello";
    }
}

ResponseEntity 方式

@RestController
public class HelloController {

  @GetMapping("/hello")
  public ResponseEntity<String> restController(){  
    return ResponseEntity.ok()
      .header("header name", "header value")
      .body("hello");
  }
}

Filter 方式

OncePerRequestFilter

@Component
public class MyResponseHeaderFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)  throws ServletException, IOException {
        response.addHeader("header name", "header value");
        filterChain.doFilter(request, response);
    }
}

Servlet Filter

@WebFilter(urlPatterns = {"/*"})
@Component
public class FirstFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        res.addHeader("header name", "header value");
        chain.doFilter(req, res);
    }
}

ResponseBodyAdvice

ResponseBodyAdvice只适用于JSON格式的Content-Type

@ControllerAdvice
public class HeaderModifierAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(final MethodParameter returnType, final Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        response.getHeaders().add("header name", "header value");
        return body;
    }
}
阅读 2128 · 发布于 2023-02-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb

扫描下方二维码关注公众号和小程序↓↓↓

扫描二维码关注我
昵称:
随便看看 换一批