【问题标题】:@RequestAttribute in a Spring MVC project does not fetch the valueSpring MVC 项目中的@RequestAttribute 不获取值
【发布时间】: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


【解决方案1】:

@RequestAttribute 不是 Spring 注释。如果你想传递一个请求参数的值,你可以这样做

@RequestMapping(value="/data/custom", method=RequestMethod.GET)  
public @ResponseBody String custom(@RequestParam("foo") String foo) {  
    System.out.println("foo value : " + foo);    //null printed      
    return foo;  
}

或者如果你想在路径中传递值,你可以这样做

@RequestMapping(value="/data/custom/{foo}", method=RequestMethod.GET)  
public @ResponseBody String custom(@PathVariable("foo") String foo) {  
    System.out.println("foo value : " + foo);    //null printed      
    return foo;  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-03
    • 2016-06-04
    • 2019-03-13
    • 2019-03-23
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多