简体   繁体   中英

@RequestAttribute in a Spring MVC project does not fetch the value

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM