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

Spring Boot About 2,244 words

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;
    }
}
Views: 3,393 · Posted: 2023-02-09

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh