Spring - 处理后修改每个请求的标头(在postHandle中) [英] Spring - Modifying headers for every request after processing (in postHandle)

查看:1002
本文介绍了Spring - 处理后修改每个请求的标头(在postHandle中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是,在处理请求后为响应添加新标头。我需要检查已处理的 HttpStatus 代码(在我的情况下未经授权401)并添加新标头。我知道Spring有拦截器,但无法修改响应,如 document

What I want to do is, adding a new header to the response after the request is processed. I need to check the processed HttpStatus code (401 unauthorized in my case) and add a new header. I know Spring has interceptors, but the response cannot be modified as stated in the document:


注意HandlerInterceptor的postHandle方法并不总是理想的适合与@ResponseBody和ResponseEntity方法一起使用。在这种情况下,HttpMessageConverter在调用postHandle之前写入并提交响应,这使得无法更改响应,例如添加标头。相反,应用程序可以实现ResponseBodyAdvice并将其声明为@ControllerAdvice bean或直接在RequestMappingHandlerAdapter上进行配置。

Note that the postHandle method of HandlerInterceptor is not always ideally suited for use with @ResponseBody and ResponseEntity methods. In such cases an HttpMessageConverter writes to and commits the response before postHandle is called which makes it impossible to change the response, for example to add a header. Instead an application can implement ResponseBodyAdvice and either declare it as an @ControllerAdvice bean or configure it directly on RequestMappingHandlerAdapter.

好吧,我实现了 ResponseBodyAdvice 。是的,它允许 body 修改,但我无法修改标头,事件无法找到从控制器返回的状态代码。

Well, I implemented the ResponseBodyAdvice. Yes, it allows body modification, but I couldn't manage to modify the headers, event couldn't find the status code returned from the controller.

使用servlet过滤器的另一个选项也不成功。我需要在 filterChain.doFilter(servletRequest,servletResponse); 调用之后添加标头。但它再次不会修改标头值。有没有办法完成这个简单的任务?

The other option, using servlet filters is not also successful. I need to add the header after filterChain.doFilter(servletRequest, servletResponse); call. But it again doesn't modify the header value. Is there a way to accomplish this easy task?

推荐答案

听起来你正在使用servlet过滤器,您可能需要做的是将servlet响应对象包装起来,该对象检测何时设置了401状态代码并在那时添加了您的自定义标头:

It sounds like you're on the right track with a servlet filter, what you probably need to do is wrap the servlet response object with one that detects when a 401 status code has been set and adds your custom header at that time:

HttpServletResponse wrappedResponse = new HttpServletResponseWrapper(response) {

  public void setStatus(int code) {
    super.setStatus(code);
    if(code == 401) handle401();
  }

  // three similar methods for the other setStatus and the two
  // versions of sendError

  private void handle401() {
    this.addHeader(...);
  }
};

filterChain.doFilter(request, wrappedResponse);

这篇关于Spring - 处理后修改每个请求的标头(在postHandle中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆