无法在postHandle拦截器中设置响应头

时间:2019-03-14 23:57:35

标签: spring-boot

最近我尝试在postHander拦截器中添加响应标头

    public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler) throws Exception{
        System.out.println("preHandle");
        response.setHeader("aaa","aaa");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);

        response.setHeader("bbb","bbb");
        System.out.println("postHandler");
    }

这是我的主要代码,但是当我向服务器发送请求时,仅aaa被添加到响应头。

enter image description here

但是控制台仍会记录

preHandle
postHandler

这意味着postHandle实际上已执行,但不添加标题。

为什么?如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这是一个有效的示例。如果我不得不猜测那件事发生在

super.postHandle(request, response, handler, modelAndView);

Web配置

@Component
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomHandleInterceptor());
    }
}

拦截器

@Component
public class CustomHandleInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("pre","works");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        response.setHeader("post","works");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        response.setHeader("complete","works");
    }
}

控制器

@Controller
public class GreetingController {
    @GetMapping("/greeting")
    public String greetingMethod(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}

响应标题

$ curl -I  http://localhost:8080/greeting
HTTP/1.1 200 
pre: works
post: works
complete: works
Content-Type: text/html;charset=UTF-8
Content-Language: en-US
Content-Length: 212
Date: Fri, 15 Mar 2019 01:42:08 GMT