2

@RequestAttribute in a Spring MVC project doesn't fetch the value.

I use a @ModelAttribute. Here foo attribute is set a value of bar

@ModelAttribute  
void beforeInvokingHandlerMethod(HttpServletRequest request) 
{  
    request.setAttribute("foo", "bar");  
}

I try to invoke the request attribute value for foo using @RequestAttribute("foo"). But value is null.

Then I try using request.getAttribute("foo") and the value is printed. I don't know what is wrong in the following code:

@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;  
}
informatik01
  • 16,038
  • 10
  • 74
  • 104
user2240003
  • 21
  • 1
  • 2
  • I may be wrong, but I think the problem is that HttpServletRequest has a scope per request, and you need per session. use HttpSession or @SessionAtribute("foo"). – legion Apr 03 '13 at 13:13
  • Check this [StackOverflow Answer](http://stackoverflow.com/questions/13895552/some-trouble-to-understand-how-is-used-requestattribute-and-modelattribute-ann) – Usha Apr 03 '13 at 20:15
  • I can see that your code is taken from [spring-mvc-showcase](https://github.com/spring-projects/spring-mvc-showcase). Note that `@RequestAttribute` **is NOT a Spring attribute**, it is a custom made attribute. See [my answer](http://stackoverflow.com/a/19393944/814702) for the details. – informatik01 Oct 16 '13 at 02:18

1 Answers1

1

@RequestAttribute is not a Spring annotation. If you want to pass a value a request param you can do

@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;  
}

Or if you want to pass values in the path you can do

@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;  
}
denov
  • 11,180
  • 2
  • 27
  • 43