我是 Spring MVC 的新手。目前正在研究Spring MVC Showcase , 演示了 Spring MVC web 框架的特性。
我有一些问题无法理解如何在此示例中处理自定义可解析 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() 方法,它有一个说话的名字,所以看起来这个方法设置了一个属性,它有 name=foo 和 value=bar,在 HttpServletRequest 对象中,然后 custom() 方法可以使用这个值。
事实上我的输出是:
Got 'foo' request attribute value 'bar'
为什么在custom()方法之前调用beforeInvokingHandlerMethod()?
为什么 beforeInvokingHandlerMethod() 被 @ModelAttribute 注释?在这种情况下,这意味着什么?
最佳答案
RequestAttribute
只是您在表单提交中传递的参数。让我们用一个示例来理解
假设我有下面的表格
<form action="...">
<input type=hidden name=param1 id=param1 value=test/>
</form>
现在,如果我有下面的 Controller ,它与请求 url 映射,而请求 url 与表单提交映射,如下所示。
@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("param1") String param1 ) {
// Here, I will have value of param1 as test in String object which will be mapped my Spring itself
}
关于java - 了解Spring MVC中@ModelAttribute和@RequestAttribute注解的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13895552/