【发布时间】:2013-04-03 12:39:13
【问题描述】:
Spring MVC 项目中的@RequestAttribute 不获取值。
我使用 @ModelAttribute。这里foo属性设置了bar的值
@ModelAttribute
void beforeInvokingHandlerMethod(HttpServletRequest request)
{
request.setAttribute("foo", "bar");
}
我尝试使用@RequestAttribute("foo") 调用foo 的请求属性值。但值为空。
然后我尝试使用request.getAttribute("foo") 并打印该值。我不知道下面的代码有什么问题:
@RequestAttribute("foo").
@RequestMapping(value="/data/custom", method=RequestMethod.GET)
public @ResponseBody String custom(@RequestAttribute("foo") String foo, HttpServletRequest request) {
System.out.println("foo value : " + foo); //null printed
System.out.println("request.getAttribute : " + request.getAttribute("foo")); //value printed
return foo;
}
【问题讨论】:
-
我可能错了,但我认为问题在于 HttpServletRequest 每个请求都有一个范围,并且您需要每个会话。使用 HttpSession 或 @SessionAtribute("foo")。
-
我可以看到你的代码取自spring-mvc-showcase。请注意,
@RequestAttribute不是 Spring 属性,它是自定义属性。详情请见my answer。
标签: java spring spring-mvc spring-annotations