SPRINGMVC4 (7) Model View method source code synthesis analysis

Source: Internet
Author: User

In full web development. SPRINGMVC primarily acts as a control layer. It accepts requests from the view layer. Gets the view-level request data and then the business logic processing of the data. Then it encapsulates the model data required by the view layer, and then directs the data to the view interface such as JSP.
In the front, we pass the analysis of the @requestmapping and method into the binding, finished the control layer of the view layer data handover, and then the business logic processing mainly by the service layer. So the next key is how to direct the view data into a particular view .

In a broad sense, a view is not a single-fingered front-end interface such as jsp\html. We may need to give the background interface to Android, iOS, etc., and discard the view interface guidance, such as pure data flow output to front-end Ajax requests, because of the front-end separation.

At this point, our view can be JSON view, XML view, even PDF view, Excel view, etc.

SPRINGMVC provides us with a variety of ways to output model data:

Output Path function Description
Modelandview Set the processing method return type to Modelandview. It encapsulates our model data and indicates the view orientation at the same time.

@modelAttribute After the method is annotated, the participating objects are placed in the data model.

Map and model When entering into Org.springframework.ui.Model or Org.springframework.ui.ModelMap or Java.util.Map, when the method returns, the data in the map is actively added to the model itself
@SessionAttributes Staging a property in the model into HttpSession so that the properties are shared between multiple requests

Below we mainly introduce Modelandview
Modelandview (hereinafter referred to as MAV) is like its name. Both the model data and the view information are included. We return a MAV. SPRINGMVC will forward the model data to the appropriate view interface.
Before learning the usage of Modelandview. We'll first learn two important parts of it in a dismembered way.

1. Model

Model is an interface in which we can simply interpret the model's implementation class as a map and return it to the view layer in the form of a key-value pair. In Springmvc, before each method is triggered by a front-end request, an implied model object is created as the storage container for the model data.

This is a request-level model data. We are able to read these model data in front-end pages such as JSPs through the relevant APIs such as HttpServletRequest.
In the model. Definitions have for example the following frequently used interface methods:

    /** * Add key Value property pair */Model AddAttribute (String attributename, Object AttributeValue);/** * The type of the property is the key to join the genus */Model AddAttribute (Object attributevalue);/** * Joins the collection property with the type of the property and collection, assuming that there is a overwrite of the same type */Model addallattributes (collection<?> attributevalues);/** * Copy the contents of the attributes into the current model * Assuming that the current model has the same content. will be overwritten * /Model addallattributes (map<string,?> attributes);/** * Copy the contents of the attributes into the current model * Assuming that the current model has the same content and will not be overwritten */Model mergeattributes (map<string,?> attributes);/** * Infer if there is a corresponding attribute value */    BooleanContainsattribute (String attributename);/** * Convert the current model to map */Map<string, object> asmap ();

Suppose we join a property that does not specify a key name. We call this anonymous data binding, which follows rules such as the following:
1. For normal data types, we directly use the type (first letter lowercase) as the key value
2. For collection types (collection interfaces, including arrays), the resulting model object property is named "Simple class name (first letter lowercase)" + "list", such as list-generated model object property named "Stringlist", and list-generated model object property named " Usermodellist ".

In Modelandview, many of our other operations are to directly manipulate Modelmap and map to complete our model number preparation. Modelmap inherits from Java.util.LinkedHashMap.

On the basis of linkedhashmap, it has added a lot of convenient construction methods such as:

publicModelMap(String attributeName, Object attributeValue) {    addAttribute(attributeName, attributeValue);}publicaddAllAttributes(Map<String, ?

> attributes) { ifnull) { putAll(attributes); } returnthis;}

Using these construction methods can further simplify our model data encapsulation.

2. View

View is also an interface that represents a response to a user's view such as a JSP file, a PDF file, and an HTML file.


It has two interface methods:
1. String getcontenttype (): Returns the content type of the view
2. void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception : Defines the rendering of the view based on the given model and Web resource.


The view interface has a number of implementation classes, such as what you see:

In spring. The behavior of the corresponding view instance is resolved through Viewresolver. Its definition is quite simple:

publicinterface ViewResolver {    //通过view name 解析View    throws Exception;}

Spring provides us with the Viewresolver implementation class to parse different view:

When we first configured the SPRINGMVC core file, we used the Internalresourceviewresolver, which is an internal resource View parser.

Resolves the returned view name to the Internalresourceview object. Internalresourceview will store the model properties returned by the Controller processor method in the corresponding request property. The request ForWord is then redirected to the destination URL via RequestDispatcher on the server side.

Let's look at the configuration example:

<bean id="viewResolver"    class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="prefix" value="/WEB-INF/views/"></property><!-- 前缀,在springMVC控制层处理好的请求后,转发配置文件夹下的视图文件 -->    <property name="suffix" value=".jsp"></property><!-- 文件后缀,表示转发到的视图文件后缀为.jsp --></bean>

After parsing the model and (and) view, take a look at our Modelandview:

 Public  class modelandview {    //View Members    PrivateObject view;//model members    PrivateModelmap model;//Whether to call the clear () method to clear the view and model    Private Booleancleared =false;/** * Empty construction method * /     Public Modelandview() {    }/** * Easy to use view name to generate a view, detailed resolution by the Dispatcherservlet View Parser */     Public Modelandview(String viewName) { This. view = ViewName; }/** * Specify a View object Generation view */     Public Modelandview(View view) { This. view = view; }/** * Specifies that the view name binds the model data at the same time. The model data is added to the original view data in append form * /     Public Modelandview(String viewName, map<string,?)

> Model) { This. view = ViewName;if(Model! =NULL) {Getmodelmap (). Addallattributes (model); } }/** * Specifies that a view object binds the model data at the same time. The model data is added to the original view data in append form * / Public Modelandview(View view, map<string,?> model) { This. view = view;if(Model! =NULL) {Getmodelmap (). Addallattributes (model); } }/** * Simple configuration: Specify the view name, add a single attribute at the same time */ Public Modelandview(String viewName, String modelname, Object modelobject) { This. view = ViewName; AddObject (ModelName, modelobject); }/** * Simple configuration: Specify a View object, adding a single attribute at the same time */ Public Modelandview(View view, String modelname, Object modelobject) { This. view = view; AddObject (ModelName, modelobject); }/** * Set Current view name * / Public void Setviewname(String viewName) { This. view = ViewName; }/** * Gets the view name. Assumes that the current View property is a view and not a name (String) returns null */ PublicStringGetviewname() {return( This. ViewinstanceofString? (String) This. View:NULL); }/** * Set Current View object * / Public void Setview(View view) { This. view = view; }/** * Gets the view, assuming a non-view instance, returns Null * / PublicViewGetView() {return( This. ViewinstanceofView? (View) This. View:NULL); }/** * Infer if the current view exists * / Public Boolean Hasview() {return( This. View! =NULL); }/** * Get model map. If NULL is assumed, create a new * / PublicModelmapGetmodelmap() {if( This. Model = =NULL) { This. Model =NewModelmap (); }return This. Model; }/** * Same Getmodelmap * * PublicMap<string, object>Getmodel() {returnGetmodelmap (); }/** * Add a single key-value pair attribute */ PublicModelandviewAddObject(String AttributeName, Object AttributeValue) {Getmodelmap (). AddAttribute (AttributeName, AttributeValue);return This; }/** * Add attribute as Property type key */ PublicModelandviewAddObject(Object AttributeValue) {Getmodelmap (). AddAttribute (AttributeValue);return This; }/** * Add all attributes from map to member properties Modelmap * / PublicModelandviewaddallobjects(map<string,?> modelmap) {Getmodelmap (). Addallattributes (Modelmap);return This; }/** * Clears the view model. and set to empty state * / Public void Clear() { This. View =NULL; This. Model =NULL; This. cleared =true; }/** * Inferred if the view and model are not included */ Public Boolean IsEmpty() {return( This. View = =NULL&& Collectionutils.isempty ( This. model)); }}

SPRINGMVC4 (7) Model View method source code synthesis analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.