繁体   English   中英

Spring MVC项目中的@RequestAttribute不会获取值

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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