【发布时间】:2012-12-03 10:48:43
【问题描述】:
我是 Spring MVC 的新手。目前我正在研究Spring MVC Showcase,它演示了Spring MVC web框架的特性。
我在理解此示例中如何处理自定义可解析 Web 参数时遇到了一些问题。
在实践中,我有以下情况。在我的 home.jsp 视图中,我有以下链接:
<a id="customArg" class="textLink" href="<c:url value="/data/custom" />">Custom</a>
此链接会生成一个指向以下 URL 的 HTTP 请求:"/data/custom"
包含处理此请求的方法的控制器类具有以下代码:
@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 Request 由自定义方法处理。
我很难理解 @RequestAttribute 批注的作用。我认为,在这种情况下,它将名为 foo 的请求属性绑定到一个新的 String foo 变量。但是这个属性是从哪里来的呢?这个变量是 Spring 占用的吗?
好的,我的想法是这个请求属性取自 HttpServletRequest 对象。我是这么认为的,因为在这个类中,我也有 beforeInvokingHandlerMethod() 方法,它有一个说话的名字,所以这个方法似乎设置了一个属性,有 name=foo em> 和 value=bar,在 HttpServletRequest 对象中,然后 custom() 方法可以使用这个值。
其实我的输出是:
得到'foo'请求属性值'bar'
为什么在 custom() 方法之前调用 beforeInvokingHandlerMethod()?
以及为什么 beforeInvokingHandlerMethod() 被 @ModelAttribute 注释所注释?在这种情况下是什么意思?
【问题讨论】:
标签: java spring spring-mvc data-binding spring-annotations