赞
踩
背景:在jwt认证中,过期access_token换取新的token,需要通过响应头返回给客户端
OncePerRequestFilter是Spring Boot里面的一个过滤器抽象类,其同样在Spring Security里面被广泛用到,这个过滤器抽象类通常被用于继承实现并在每次请求时只执行一次过滤。
@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 又称 Servlet 过滤器,它是在 Servlet 2.3 规范中定义的,能够对 Servlet 容器传给 Web 资源的 request 对象和 response 对象进行检查和修改。
- 在 Web 资源被访问前,检查 request 对象,修改请求头和请求正文,或对请求进行预处理操作。
- 将请求传递到下一个过滤器或目标资源。
- 在 Web 资源被访问后,检查 response 对象,修改响应头和响应正文。
@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只适用于JSON格式的Content-Type。
ResponseBodyAdvice接口和RequestBodyAdvice接口类似,
RequestBodyAdvice是请求到Controller之前拦截,做相应的处理操作,
ResponseBodyAdvice是对Controller返回的{@code @ResponseBody}or a {@code ResponseEntity} 后,{@code HttpMessageConverter} 类型转换之前拦截, 进行相应的处理操作后,再将结果返回给客户端
@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; } }
@RestController
public class HelloController {
@GetMapping("/hello")
public String viewController(HttpServletResponse response){
response.setHeader("header name", "header value");
return "hello";
}
}
@RestController
public class HelloController {
@GetMapping("/hello")
public ResponseEntity<String> restController(){
return ResponseEntity.ok()
.header("header name", "header value")
.body("hello");
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。