Spring 2.5之 @ModelAtrribute

來源:互聯網
上載者:User

 很久沒來了,來mark一個,最近用spring的MVC,碰到ModelAtrribute這個標註,感覺相對其他標註比較難於理解一點,看了一遍原始碼,梳理一下,做下記錄。

ModelAtrribute標註本身很簡單,看下他的定義:

/** * Annotation that binds a method parameter or method return value * to a named model attribute, exposed to a web view. Supported * for {@link RequestMapping} annotated handler classes. * * <p>Can be used to expose command objects to a web view, using * specific attribute names, through annotating corresponding * parameters of a {@link RequestMapping} annotated handler method). * * <p>Can also be used to expose reference data to a web view * through annotating accessor methods in a controller class which * is based on {@link RequestMapping} annotated handler methods, * with such accessor methods allowed to have any arguments that * {@link RequestMapping} supports for handler methods, returning * the model attribute value to expose. * * @author Juergen Hoeller * @since 2.5 */@Target({ElementType.PARAMETER, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ModelAttribute {/** * The name of the model attribute to bind to. * <p>The default model attribute name is inferred from the declared * attribute type (i.e. the method parameter type or method return type), * based on the non-qualified class name: * e.g. "orderAddress" for class "mypackage.OrderAddress", * or "orderAddressList" for "List<mypackage.OrderAddress>". */String value() default "";}

它可以標註方法(method)和參數(parameter),當標註參數時,表示從session或者impitmodel中擷取這個屬性對象,然後從request參數擷取一些屬性值來覆蓋ModelAttribute標註的對象中的部分屬性。

例如:

@RequestMappingpublic void addOrder(@ModelAttribute("order") Order order){ .....}

對應解析這段代碼的地方在org.springframework.web.bind.annotation.support.HandlerMethodInvoker#resolveHandlerArguments和resolveModelAttribute中,可以仔細看下,另外你會發現,如果參數本身就是一個POJO時,其實你可以不用寫ModelAttribute,它會自動根據參數類型來解析出名稱並執行與有ModelAttribute標註時一樣的邏輯。

標註方法時,表示該方法執行的結果放入到最後的modelMap中,key是ModelAttribute標註的名稱或者從型別參數正常化而來,如果沒有RequestMapping標註,則每次執行其
他的RequestMapping的方法時都要先執行這個方法,如果有RequestMapping標註,則只是在該方法執行的時候才將該返回結果放入到modelMap中,注意返回對象可以是

Model,Map,View,String或者其他非簡單對象,但不能是Long,int,Class這些類型。

對應解析代碼在org.springframework.web.bind.annotation.support.HandlerMethodInvoker#invokeHandlerMethod和org.springframework.web.servlet.mvc.annotation。AnnotationMethodHandlerAdapter#getModelAndView 中。getModelAndView 主要是將執行方法後得到的結果放入到modelMap中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.