gpt4 book ai didi

java - Spring 3 HandlerInterceptor 将信息传递给 Controller

转载 作者:行者123 更新时间:2023-11-30 07:59:09 25 4
gpt4 key购买 nike

我已经设置了一个 Spring HandlerInterceptor 来向 HttpServletRequest 添加一个属性,以便能够从 Controller 读取它,遗憾的是这似乎不起作用,这对我来说似乎很奇怪。我做错了吗?知道如何将数据从拦截器传输到 Controller 吗?

这里是两个受影响类的简化代码

public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
request.setAttribute("my-role", "superman");
}
[...]
}

@RestController
@RequestMapping("Test")
public class TestController {
public final Logger logger = LoggerFactory.getLogger(getClass());

@RequestMapping(value = "something")
public void something(HttpServletRequest request) {
logger.info(request.getAttribute("my-role"));
}

[...]
}

request.getAttribute("my-role") 返回 null...但如果我在 HandlerInterceptor 的 postHandle 中读取它,它会返回异常值,我觉得我遗漏了什么...

编辑:我发现通过“request.getSession().setAttribute” session 很有用,但我仍然不明白为什么请求本身在这个用例中不起作用。

最佳答案

你能尝试使用 session 而不是像下面这样的请求吗?

  public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
...
HttpSession session = request.getSession();
session.setAttribute("attributeName", objectYouWantToPassToHandler);
....
}
In your handler handleRequest method:

public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {

....
HttpSession session = request.getSession();
objectYouWantToPassToHandler objectYouWantToPassToHandler = session.getAttribute("attributeName");
....


}

关于java - Spring 3 HandlerInterceptor 将信息传递给 Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39618738/

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