Viewresolver is defined as follows:
Public Interface viewresolver { throws Exception; }
In spring, there are several common viewresolver:
Internalresourceviewresolver |
Resolves a logical view name to a path |
Beannameviewresolver |
Resolves the logical view name to the Bean's Name property, thus finding the bean that defines the view based on the Name property |
Resourcebundleresolver |
As with Beannameviewresolver, only the defined View-bean are in a properties file, and the properties file is loaded with this class |
Xmlviewresolver |
Just like Resourcebundleresolver, the definition of View-bean in an XML file, using this class to load an XML file |
The spring framework provides a good support for us when we need multiple viewresolver, so we can just define multiple viewresolver in [Spring-dispatcher-name]-servlet.xml]. Such as:
<!--defining a JSP View parser - <BeanID= "Jspviewresolver"class= "Org.springframework.web.servlet.view.InternalResourceViewResolver"> < Propertyname= "prefix"value= "/web-inf/"></ Property> < Propertyname= "suffix"value= ". jsp"></ Property> < Propertyname= "Order"value= "1" /></Bean><BeanID= "Freemarkerviewresolver"class= "Com.founder.web.commom.springmvc.view.ExtFreeMarkerViewResolver"> < Propertyname= "ContentType"value= "text/html; charset=utf-8"/> < Propertyname= "Exposerequestattributes"value= "false"/> < Propertyname= "Exposesessionattributes"value= "false"/> < Propertyname= "Exposespringmacrohelpers"value= "true"/> < Propertyname= "Cacheunresolved"value= "false"/> < Propertyname= "Order"value= "0" /></Bean>
Dispatcherservlet loads all the viewresolver into a list and resolves it by priority.
Note: The smaller the value in ①order, the higher the priority.
② and the priority of Viewresolver with ID viewresolver is the lowest.
Ps:
If a parser does not find a suitable view, spring looks in the context to see if another parser is configured. If there is, it will continue parsing, otherwise, srping will throw one Exception
.
Keep in mind that when a view resolver cannot find the appropriate view, it may return a null value. However, not every parser does this. This is because, in some cases, the parser may not be able to detect whether a view that meets the requirements exists. For example, InternalResourceViewResolver
it is called internally RequestDispatcher
. Request distribution is the only way to check the existence of a JSP file, unfortunately, this method can only be used once. The same problem is VelocityViewResolver
found in other parsers as well. When using these parsers, it is best to read their Javadoc carefully to see if the required parser is unable to find a view that does not exist. The side effect of this problem is that if the InternalResourceViewResolver
parser is not placed at the end of the chain, the InternalResourceViewResolver
parser behind it will not be used at all, because it InternalResourceViewResolver
always returns a view!
Spring Web MVC Multi-viewresolver View resolver solution