【问题标题】:Understanding the use of @ModelAttribute and @RequestAttribute annotations in Spring MVC了解Spring MVC中@ModelAttribute和@RequestAttribute注解的使用
【发布时间】: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


    【解决方案1】:

    RequestAttribute 只不过是您在表单提交中传递的参数。让我们通过一个示例来理解

    假设我有以下表格

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

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

    【讨论】:

    • mmm 让我很好地理解了这件事:所以当我通过 @ModelAttribute 注释我的 beforeInvokingHandlerMethod() 方法时,如果我正确传递了一个带有“foo”、“bar”值的表单,那是同样的事情?在这个方法中我做了 request.setAttribute("foo", "bar"); ?
    • Excatly,你是正确的,为了更好地理解 ModelAttribute,你可以访问 Spring MVC 的官方文档static.springsource.org/spring/docs/3.1.x/javadoc-api/org/… 和blog.trifork.nl/2009/05/14/simple-forms-with-spring-mvc-2-5
    • 我已经阅读了这个文档,但是我在理解它时遇到了一些问题:-(实际上你说我当我有一个由 ModelAttribute 注释注释的方法时,我正在绑定一个方法参数到一个命名的模型属性,然后我可以通过使用 RequestAttribute 注释在其他方法中使用它?但在我的情况下,我绑定的参数是什么?是名为“foo”的参数以“bar”为值吗?谢谢你真的很善良:-)
    • 不客气,如果你愿意,现在接受并支持我的回答:)
    • @AndreaNobili 谢谢好友。
    猜你喜欢
    • 1970-01-01
    • 2012-12-04
    • 2014-05-04
    • 2020-11-26
    • 2021-04-12
    • 1970-01-01
    • 2015-06-04
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多