![](/img/trans.png)
[英]Understanding the use of @ModelAttribute and @RequestAttribute annotations in Spring MVC
[英]@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.