gpt4 book ai didi

spring-boot - 无法在 postHandle 拦截器中设置响应 header

转载 作者:行者123 更新时间:2023-12-05 07:24:48 25 4
gpt4 key购买 nike

最近我尝试在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 被添加到响应 header 。

enter image description here

但是控制台还是有日志

preHandle
postHandler

意思是postHandle确实被执行了,但是没有添加header。

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

最佳答案

这是一个工作示例。如果我不得不猜测它发生在

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

网络配置

@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

@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

关于spring-boot - 无法在 postHandle 拦截器中设置响应 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com