我对 Spring MVC 还很陌生。目前我正在学习Spring MVC 展示 https://github.com/spring-projects/spring-mvc-showcase,演示了 Spring MVC Web 框架的功能。
我无法理解此示例中如何处理自定义可解析 Web 参数。
在实践中我有以下情况。在我的home.jsp查看我有以下链接:
<a id="customArg" class="textLink" href="<c:url value="/data/custom" />">Custom</a>
此链接生成一个针对 URL 的 HTTP 请求:“/数据/自定义”
包含处理此请求的方法的控制器类具有以下代码:
@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 的请求属性绑定到一个新的 String foo 变量。但这个属性是从哪里获取的呢? Spring 是否使用了该变量?
好的,我的想法是这个请求属性取自 HttpServletRequest 对象。我这么认为是因为,在这堂课上,我也有beforeInvokingHandlerMethod()具有说话名称的方法,因此该方法似乎设置了一个属性,该属性具有name=foo and 值=条,在 HttpServletRequest 对象内,然后 custom() 方法可以使用该值。
事实上我的输出是:
获取“foo”请求属性值“bar”
Why the beforeInvokingHandlerMethod()在之前调用custom() method?
以及为什么beforeInvokingHandlerMethod()注释为@ModelAttribute注解?在这种情况下这意味着什么?