Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ModelAndView in SpringMVC

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to use ModelAndView in SpringMVC, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

(1) use the ModelAndView class to store the processed result data and display the view of the data. In terms of name, Model in ModelAndView represents the model, and View represents the view, which well explains the purpose of this class. After the business processor calls the model layer to process the user request, the result data is stored in the model property of the class, the view information to be returned is stored in the view property of the class, and then the ModelAndView is returned to the Spring MVC framework. The framework parses the object by calling the view parser defined in the configuration file, and finally displays the resulting data on the specified page.

Specific functions:

1. Return to the specified page

The ModelAndView constructor can specify the name of the returned page

You can also jump to the specified page through the setViewName () method

2. Return the required value

Using addObject () to set the value to be returned, addObject () has several different parameter methods that can default and specify the name of the returned object.

1. [its source code]: familiar with the usage of a class, it is best to start with its source code.

Public class ModelAndView {/ * * View instance or view name String * / private Object view / / this attribute is used to store the returned view information / * * ModelMap * / private ModelMap model;// this attribute is used to store the processed result data / * Indicates whether or not this instance has been cleared with a call to {@ link # clear ()}. * / private boolean cleared = false; / * * Default constructor for bean-style usage: populating bean * properties instead of passing in constructor arguments. * @ see # setView (View) * @ see # setViewName (String) * / public ModelAndView () {} / * Convenient constructor when there is no model data to expose. * Can also be used in conjunction with addObject. * @ param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @ see # addObject * / public ModelAndView (String viewName) {this.view = viewName;} / * Convenient constructor when there is no model data to expose. * Can also be used in conjunction with addObject. * @ param view View object to render * @ see # addObject * / public ModelAndView (View view) {this.view = view;} / * Creates new ModelAndView given a view name and a model. * @ param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @ param model Map of model names (Strings) to model objects * (Objects). Model entries may not be null, but the * model Map may be null if there is no model data. * / public ModelAndView (String viewName, Map model) {this.view = viewName; if (model! = null) {getModelMap (). AddAllAttributes (model);}} / * * Creates new ModelAndView given a View object and a model. * Note: the supplied model data is copied into the internal * storage of this class. You should not consider to modify the supplied * Map after supplying it to this class * @ param view View object to render * @ param model Map of model names (Strings) to model objects * (Objects). Model entries may not be null, but the * model Map may be null if there is no model data. * / public ModelAndView (View view, Map model) {this.view = view; if (model! = null) {getModelMap (). AddAllAttributes (model);}} / * * Convenient constructor to take a single model object. * @ param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @ param modelName name of the single entry in the model * @ param modelObject the single model object * / public ModelAndView (String viewName, String modelName, Object modelObject) {this.view = viewName; addObject (modelName, modelObject);} / * Convenient constructor to take a single model object. * @ param view View object to render * @ param modelName name of the single entry in the model * @ param modelObject the single model object * / public ModelAndView (View view, String modelName, Object modelObject) {this.view = view; addObject (modelName, modelObject);} / * * Set a view name for this ModelAndView, to be resolved by the * DispatcherServlet via a ViewResolver. Will override any * pre-existing view name or View. * / public void setViewName (String viewName) {this.view = viewName;} / * * Return the view name to be resolved by the DispatcherServlet * via a ViewResolver, or null if we are using a View object. * / public String getViewName () {return (this.view instanceof String? (String) this.view: null);} / * * Set a View object for this ModelAndView. Will override any * pre-existing view name or View. * / public void setView (View view) {this.view = view;} / * * Return the View object, or null if we are using a view name * to be resolved by the DispatcherServlet via a ViewResolver. * / public View getView () {return (this.view instanceof View? (View) this.view: null);} / * * Indicate whether or not this ModelAndView has a view, either * as a view name or as a direct {@ link View} instance. * / public boolean hasView () {return (this.view! = null);} / * Return whether we use a view reference, i.e. True * if the view has been specified via a name to be resolved by the * DispatcherServlet via a ViewResolver. * / public boolean isReference () {return (this.view instanceof String);} / * * Return the model map. May return null. * Called by DispatcherServlet for evaluation of the model. * / protected Map getModelInternal () {return this.model;} / * * Return the underlying ModelMap instance (never null). * / public ModelMap getModelMap () {if (this.model = = null) {this.model = new ModelMap ();} return this.model;} / * Return the model map. Never returns null. * To be called by application code for modifying the model. * / public Map getModel () {return getModelMap ();} / * * Add an attribute to the model. * @ param attributeName name of the object to add to the model * @ param attributeValue object to add to the model (never null) * @ see ModelMap#addAttribute (String, Object) * @ see # getModelMap () * / public ModelAndView addObject (String attributeName, Object attributeValue) {getModelMap (). AddAttribute (attributeName, attributeValue); return this;} / * * Add an attribute to the model using parameter name generation. * @ param attributeValue the object to add to the model (never null) * @ see ModelMap#addAttribute (Object) * @ see # getModelMap () * / public ModelAndView addObject (Object attributeValue) {getModelMap () .addAttribute (attributeValue); return this;} / * Add all attributes contained in the provided Map to the model. * @ param modelMap a Map of attributeName-> attributeValue pairs * @ see ModelMap#addAllAttributes (Map) * @ see # getModelMap () * / public ModelAndView addAllObjects (Map modelMap) {getModelMap () .addAllAttributes (modelMap); return this;} / * Clear the state of this ModelAndView object. * The object will be empty afterwards. *

Can be used to suppress rendering of a given ModelAndView object * in the postHandle method of a HandlerInterceptor. * @ see # isEmpty () * @ see HandlerInterceptor#postHandle * / public void clear () {this.view = null; this.model = null; this.cleared = true;} / * Return whether this ModelAndView object is empty, * i.e. Whether it does not hold any view and does not contain a model. * / public boolean isEmpty () {return (this.view = = null & & CollectionUtils.isEmpty (this.model));} / * * Return whether this ModelAndView object is empty as a result of a call to {@ link # clear} * i.e. Whether it does not hold any view and does not contain a model. *

Returns false if any additional state was added to the instance * after the call to {@ link # clear}. * @ see # clear () * / public boolean wasCleared () {return (this.cleared & & isEmpty ());} / * * Return diagnostic information about this model and view. * / @ Override public String toString () {StringBuilder sb = new StringBuilder ("ModelAndView:"); if (isReference ()) {sb.append ("reference to view with name'") .append (this.view) .append ("'");} else {sb.append ("materialized View is [") .append (this.view) .append (']');} sb.append ("; model is") .append (this.model); return sb.toString ();}

There are 7 constructors in the source code, how to use it? It's a key point.

Construct ModelAndView object when the controller finishes processing the request, it usually returns the ModelAndView object that contains the view name or view object and some model properties to the DispatcherServlet.

Therefore, it is often necessary to construct ModelAndView objects in the controller.

The ModelAndView class provides several overloaded constructors and some convenient methods that allow you to construct ModelAndView objects according to your preferences. These constructors and methods support view names and view objects in a similar way.

Through the ModelAndView constructor, you can specify the name of the returned page, or you can jump to the specified page through the setViewName () method, and use addObject () to set the value to be returned. AddObject () has several different parameter methods, which can default and specify the name of the returned object.

(1) when you have only one model property to return, you can specify that property in the constructor to construct the ModelAndView object:

Package com.apress.springrecipes.court.web;... Import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class WelcomeController extends AbstractController {public ModelAndView handleRequestInternal (HttpServletRequest request, HttpServletResponse response) throws Exception {Date today = new Date (); return new ModelAndView ("welcome", "today", today);}

(2) if you have more than one property to return, you can pass them to a Map and then construct the ModelAndView object.

Package com.apress.springrecipes.court.web;... Import org.springframework.web.servlet.ModelAndView; import org. Springframework.web.servlet.mvc.AbstractController; public class ReservationQueryController extends AbstractController {... Public ModelAndView handleRequestInternal (HttpServletRequest request, HttpServletResponse response) throws Exception {... Map model = new HashMap (); if (courtName! = null) {model.put ("courtName", courtName); model.put ("reservations", reservationService.query (courtName));} return new ModelAndView ("reservationQuery", model);}}

Spring also provides ModelMap, which is an java.util.Map implementation that automatically generates the names of model properties based on the specific type of model properties.

Package com.apress.springrecipes.court.web;... Import org.springframework.ui.ModelMap; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class ReservationQueryController extends AbstractController {... Public ModelAndView handleRequestInternal (HttpServletRequest request, HttpServletResponse response) throws Exception {... ModelMap model = new ModelMap (); if (courtName! = null) {model.addAttribute ("courtName", courtName); model.addAttribute ("reservations", reservationService.query (courtName));} return new ModelAndView ("reservationQuery", model);}}

Here, I would like to say one more thing: the ModelMap object is mainly used to pass control methods to process data to the result page.

In other words, we can put the data needed on the result page into the ModelMap object, which is similar to the setAttribute method of the request object, which is used to pass the processed data during a request.

Pass parameters to the page in the following ways:

The method of addAttribute (String key,Object value) / / modelMap

The data in modelmap can be obtained and displayed on the page through the el variable ${key} or a series of data display tags of bboss.

Modelmap itself cannot set the url address alias or physical jump address of the page jump, so we can set the jump url address alias or physical jump address through the return value of the controller method. For example:

Public String xxxxmethod (String someparam,ModelMap model) {/ / omission method processing logic places data into the ModelMap object model, and the second parameter can be any java type model.addAttribute ("key", someparam);. / / return the jump address return "path:handleok";}

The simplest ModelAndView of these constructors is the return of the name that holds the View, after which the View name is resolved by the view resolver, that is, the instance that implements the org.springframework.web.servlet.View interface

For example: InternalResourceView or JstlView and so on: ModelAndView (String viewName)

If you want to return Model objects, you can use Map to collect these Model objects, and then set them to ModelAndView, using the following version:

ModelAndView:ModelAndView (String viewName, Map model), set the key and value values in the Map object, and then take them out in the view. If you just want to return a Model object, you can use the following ModelAndView version:

ModelAndView (String viewName, String modelName, Object modelObject), where modelName, you can take out the Model in the view and display

The ModelAndView class provides objects that implement the View interface as parameters for View:

ModelAndView (View view) ModelAndView (View view, Map model) ModelAndView (View view, String modelName, Object modelObject)

2 [method use]: there are two ways to set view for a ModelAndView instance: setViewName (String viewName) and setView (View view).

The former uses viewName, while the latter uses pre-constructed View objects. The former is more commonly used. In fact, View is an interface, not a concrete class that can be constructed, and we can only get an instance of View through other ways. For viewName, it can be either the name of the jsp or the name of the tiles definition, depending on how the ViewNameResolver used understands the view name. How to get an example of View will be studied later.

However, it is more complicated to set model to the ModelAndView instance. There are three methods you can use:

AddObject (Object modelObject); addObject (String modelName, Object modelObject); addAllObjects (Map modelMap)

3 [brief introduction to function]:

The ModelAndView object serves two purposes:

Function 1: set the redirection address, as shown below (this is also the main difference between ModelAndView and ModelMap)

ModelAndView view = new ModelAndView ("path:ok")

Function 2: it is used to pass the control method to process the result data to the result page, that is to say, we can put the data needed on the result page into the ModelAndView object

Its role is similar to that of the setAttribute method of the request object, which is used to pass processed data during a request. Pass parameters to the page in the following ways:

AddObject (String key,Object value)

The above is all the contents of the article "how to use ModelAndView in SpringMVC". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report