了解Spring MVC中@ModelAttribute和@RequestAttribute批注的用法


问题内容

我在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请求由自定义方法处理。

我在理解 @RequestAttribute 批注的确切功能时遇到了一些问题。我认为在这种情况下,它将名为foo的请求属性绑定到新的String
foo变量。但是,此属性来自何处?Spring会采用此变量吗?

好的,我的想法是该请求属性取自HttpServletRequest对象。我想是因为在这个类中,我还有一个具有语音名称的
beforeInvokingHandlerMethod()
方法,因此看来该方法设置了一个属性,该属性在HttpServletRequest对象内具有 name = foovalue = bar
,然后因此custom()方法可以使用此值。

实际上,我的输出是:

得到了’foo’请求属性值’bar’

为什么在 custom()* 方法之前调用 beforeInvokingHandlerMethod()*

以及为什么用 @ModelAttribute* 注释对 beforeInvokingHandlerMethod()
进行注释?在这种情况下是什么意思?
*


问题答案:

RequestAttribute 是什么,但你在表单提交已传递的参数。让我们看一个示例

假设我有以下表格

<form action="...">
<input type=hidden name=param1 id=param1 value=test/>
</form>

现在,如果我有下面的控制器,它与请求的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
}