我是 Spring MVC 的新手。
这段时间我在研究Spring MVC showcase示例可从 STS 仪表板下载。
我在理解如何在此示例中处理自定义可解析 Web 参数时遇到了一些问题。
在实践中我有以下情况:
在我的 home.jsp View 中,我有以下链接:
<a id="customArg" class="textLink" href="<c:url value="/data/custom" />">Custom</a>
此链接生成针对 URL 的 HTTP 请求:"/data/custom"
包含处理此请求的方法的 Controller 类具有以下代码:
@Controller
public class CustomArgumentController {
@ModelAttribute
void beforeInvokingHandlerMethod(HttpServletRequest request) {
request.setAttribute("foo", "bar");
}
@RequestMapping(value="/data/custom", method=RequestMethod.GET)
public @ResponseBody String custom(@RequestAttribute("foo") String foo) {
return "Got 'foo' request attribute value '" + foo + "'";
}
}
处理这个 HTTP 请求的方法是 custom()
因此,当单击上一个链接时,HTTP 请求由自定义方法处理...
我在理解 @RequestAttribute
注释时遇到问题。
我认为,在这种情况下,它将名为 foo 的请求属性绑定(bind)到一个新的 String foo
变量。
但是……这个属性是从哪里取来的?这个变量是Spring取的吗?
好的...我的想法是这个请求属性取自 HttpServletRequest
对象...
我认为这是因为,在这个类中,我也有 beforeInvokingHandlerMethod()
方法,它有一个 speacking name...所以看起来这个方法设置了一个属性,它有 name=foo
和 value=bar
,在 HttpServletRequest
对象中...然后 custom()
方法可以使用这个值...
事实上我的输出是:
得到'foo'请求属性值'bar'
为什么beforeInvokingHandlerMethod()
在custom()
方法之前调用?
为什么 beforeInvokingHandlerMethod()
被 @ModelAttribute
注解了?这个案例是什么意思?
最佳答案
你对@RequestAttribute
的假设是正确的,它不需要在beforeInvokingHandlerMethod
中设置。假设您有一个映射到 /data/init
的方法,它将请求转发到 /data/custom
。在这种情况下,也可以在 init 方法中设置请求属性。
Why the beforeInvokingHandlerMethod() is called before the custom() method?
And why the beforeInvokingHandlerMethod() is annoted by @ModelAttribute annotation? what means in this case?
An @ModelAttribute on a method indicates the purpose of that method is to add one or more model attributes. Such methods support the same argument types as @RequestMapping methods but cannot be mapped directly to requests. Instead @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.
关于java - 在此 Spring MVC 展示示例中如何使用 @RequestAttribute 和 @ModelAttribute 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13919307/