SpringMVC core -- Return Value Problem, springmvc Return Value
I. SpringMVC uses ModelAndView to handle the returned value.
1. ModelAndView
Official description:
|
Holder for both Model and View in the web MVC framework.
Note that these are entirely distinct. This class merely holds
Both to make it possible for a controller to return both model
And view in a single return value.
<P> Represents a model and view returned by a handler, to be resolved
By a DispatcherServlet. The view can take the form of a String
View name which will need to be resolved by a ViewResolver object;
Alternatively a View object can be specified directly. The model
Is a Map, allowing the use of multiple objects keyed by name. |
Note:
In the springmvc framework, ModelAndView indicates that both Model and View are held. The Model and View are completely different.
This class makes it possible for a controller to return a separate value containing both model and view.
It also indicates that a processor returns a model and view, which will be parsed by DispatcherServlet.
If the View object is obtained by the view name in the form of a string, it can be parsed by the ViewResolver object.
Alternatively, you can directly specify the View object. Model is a Map type and can use key-value pairs of multiple objects.
2. here we need to understand why we use ModelAndView to handle the returned value. In fact, there are many types of returned data, which can be ModelAndView,
It can also be 'string' or 'view'. There are many other options. But they will eventually be parsed as ModelAndView objects.
Use the source code to confirm:
Org. springframework. web. servlet. mvc. annotation. AnnotationMethodHandlerAdapter # invokeHandlerMethod
In this method:
Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);ModelAndView mav = methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest);
The result is the return value after the handler method is called.
Use the mehtodInvoker. getModelAndView () method to parse the result into a ModelAndView object.
Let's take a look at the specific process:
public ModelAndView getModelAndView(Method handlerMethod, Class<?> handlerType, Object returnValue, ExtendedModelMap implicitModel, ServletWebRequest webRequest) throws Exception { ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(handlerMethod, ResponseStatus.class); if (responseStatusAnn != null) { HttpStatus responseStatus = responseStatusAnn.value(); String reason = responseStatusAnn.reason(); if (!StringUtils.hasText(reason)) { webRequest.getResponse().setStatus(responseStatus.value()); } else { webRequest.getResponse().sendError(responseStatus.value(), reason); } // to be picked up by the RedirectView webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, responseStatus); responseArgumentUsed = true; } // Invoke custom resolvers if present... if (customModelAndViewResolvers != null) { for (ModelAndViewResolver mavResolver : customModelAndViewResolvers) { ModelAndView mav = mavResolver.resolveModelAndView( handlerMethod, handlerType, returnValue, implicitModel, webRequest); if (mav != ModelAndViewResolver.UNRESOLVED) { return mav; } } } if (returnValue instanceof HttpEntity) { handleHttpEntityResponse((HttpEntity<?>) returnValue, webRequest); return null; } else if (AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) != null) { handleResponseBody(returnValue, webRequest); return null; } else if (returnValue instanceof ModelAndView) { ModelAndView mav = (ModelAndView) returnValue; mav.getModelMap().mergeAttributes(implicitModel); return mav; } else if (returnValue instanceof Model) { return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap()); } else if (returnValue instanceof View) { return new ModelAndView((View) returnValue).addAllObjects(implicitModel); } else if (AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class) != null) { addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel); return new ModelAndView().addAllObjects(implicitModel); } else if (returnValue instanceof Map) { return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map<String, ?>) returnValue); } else if (returnValue instanceof String) { return new ModelAndView((String) returnValue).addAllObjects(implicitModel); } else if (returnValue == null) { // Either returned null or was 'void' return. if (this.responseArgumentUsed || webRequest.isNotModified()) { return null; } else { // Assuming view name translation... return new ModelAndView().addAllObjects(implicitModel); } } else if (!BeanUtils.isSimpleProperty(returnValue.getClass())) { // Assume a single model attribute... addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel); return new ModelAndView().addAllObjects(implicitModel); } else { throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); }}
This method is very important. It describes the process of parsing the return value of the handler method to ModelAndView. It can be seen that the return value can be of many types. We suggest you take a look. This article does not describe specific types of return values.
3. From the official description, we can also see that ModelAndView is divided into two parts: Model and View. Here we will explain it in two parts. View is actually a problem of View rendering.
4. Model.
The Model mentioned here not only refers to the specific class of Model. It describes how SpringMVC stores data in the Model for use on the target page.
(1) how to store
As mentioned above, the ModelAndView object is used to handle the returned value. You can store data in the Model as follows. For example:
@RequestMapping("/testModelAndView")public ModelAndView testModelAndView() { ModelAndView mv = new ModelAndView(); mv.setViewName("success"); mv.addObject("testKey", "testValue"); return mv;}
You can use the addObject () method of the ModelAndView object to add data to the model.
In fact, you can add parameters of the Model or Map type to the method's input parameters. You can add data to the Model. For example:
@RequestMapping("/testModelAndView02")public String testModelAndView2(Map map) { map.put("testKey", "testValue"); return "success";}
Why can we add the Model data to the input parameter of the handler method by adding the Model type or Map type parameter.
The actual Map type of the input target method is BindingAwareModelMap.
Source code parsing:
Org. springframework. web. servlet. mvc. annotation. AnnotationMethodHandlerAdapter # In the invokeHandlerMethod () method:
ExtendedModelMap implicitModel = new BindingAwareModelMap (); // The Object result created here is methodInvoker. invokeHandlerMethod (handlerMethod, handler, webRequest, implicitModel );
Org. springframework. web. bind. annotation. support. HandlerMethodInvoker # In the resolveHandlerArguments () method
If (Model. class. isAssignableFrom (paramType) | Map. class. isAssignableFrom (paramType) {if (! ParamType. isAssignableFrom (implicitModel. getClass () {throw new IllegalStateException ("Argument [" + paramType. getSimpleName () + "] is of type" + "Model or Map but is not assignable from the actual model. you may need to switch "+" newer MVC infrastructure classes to use this argument. ");} args [I] = implicitModel; // assign a value in this place .}
We can see that all the Map type (including its Subtypes) or Model type (including its Subtypes) parameters in the target method will be converted to the BindingAwareModelMap type.
Here we describe the BindingAwareModelMap type:
(2) What to store
We can see from the above that the Map or Model of the key-Value Pair type is stored.
(3) Where to store
Let's look at the example below:
@RequestMapping("/testModelAndView")public ModelAndView testModelAndView() { ModelAndView mv = new ModelAndView(); mv.setViewName("success"); mv.addObject("testKey", "testValue"); return mv;}
Success. jsp
Through testing, we found that the data in the Model is stored in the Request domain by default.
5. Summary
SpringMVC uses ModelAndView to solve the handler method Return Value Problem and understand the type of handler method return value. Why does ModelAndView solve the handler method Return Value Problem?
The returned values are eventually converted to ModelAndView objects. The Model can also be used as an input parameter of the handler method. The Model mentioned here not only refers to the Model type, but also refers to the implementation of the Model or Map interface.
Type. It also understands what is stored in the Model and where it is stored. So far, the SpringMVC method's return value problem has been learned. Next, we will learn how to deal with the returned values? -- Return the handler Method
The value processing problem also refers to the view rendering problem. In addition, there are two annotations that are not described. @ SessionAttribute and @ ModelAttribute can be included in the Model. Here we will write another article to describe them separately.