Spring MVC view locator viewresolver

Source: Internet
Author: User

We already know that viewresolver is mainly responsible for returning an available view instance for dispatcherservlet Based on the logical view name in the modelandview returned by the Controller. Now is the time to uncover how viewresolver "does its duty.

Having viewresolver's responsibilities as a premise, it is no longer difficult to understand or even declare a viewresolver interface. In fact, the viewresolver interface definition is really simple, as shown below:

Public interface viewresolver {

View resolveviewname (string viewname, locale) throws exception;

}

The interface implementation class only needs to input the logical view name (viewname) and the current locale value in the form of parameters in the resolveviewname () method, and return the corresponding view instance to [17]. For how each viewresolver implementation class processes the correspondence between a specific logical view name and a specific view instance, there are differences between the implementation classes.

Most viewresolver implementation classes except Org. springframework. web. servlet. view. beanname-viewresolver implements the viewresolver interface directly or indirectly inherited from Org. springframe work. web. servlet. view. abstractcachingviewresolver. Because the re-instantiation of view for each request may cause performance loss to the web application, spring MVC adds the cache function of the view instance to the hierarchy of abstractcachingviewresolver. Abstractcachingviewresolver enables the View cache function by default. This is a reasonable default value for the production environment. However, if you want to immediately reflect the modification results in a test or development environment, you can temporarily disable the ingress actcachingviewresolver cache function through setcache (false.

Spring MVC provides a series of viewresolver implementations based on javasactcachingviewresolver. Let's take a look at their true colors.

24.4.1 available viewresolver implementation class

For ease of understanding, we can divide the viewresolver provided by spring MVC into two categories: viewresolver for a single view, and viewresolver for multiple views. The following are the details of the two types of viewresolver.

1. viewresolver for a single view type

The authentic name of viewresolver of this category should be urlbasedviewresolver (both of which inherit directly or indirectly from this class ). When using viewresolver of this type, we do not need to configure the ing between the specific logical view name and the specific view for them. Generally, you only need to specify the location of the view template. The viewresolver crawls the corresponding template file, constructs the corresponding view instance, and returns the result according to the logical view name. All of them are called viewresolver for a single view, because in this category, each specific viewresolver implementation is only responsible for one view type ing, the relationship between viewresolver and view is one to one. For example, the previously used internalresourceview-resolver is usually only responsible for capturing JSP template files at the specified position, constructing a view instance of the internalresourceview type, and returning. Velocityviewresolver only cares about the velocity template file (. VM), and map the logical view name to the view template file name, and then construct a view instance of the velocityview type to return, and so on.

The main viewresolver implementation classes of this class are as follows.

Q internalresourceviewresolver. It is the most widely used viewresolver Implementation type. It corresponds to the ing of the internalresourceview [18] view type. To put it bluntly, it is used to process the view ing of the JSP template type. If dispatcherservlet cannot find at least one viewresolver in its webapplicationcontext during initialization, internalresourceviewresolver will be used as the default viewresolver.

Q freemarkerviewresolver/velocityviewresolver. Freemarkerviewresolver and velo-cityviewresolver are responsible for finding the corresponding freemarkerview and velocityview views. They will obtain the corresponding template files based on the logical view name to the specified location, create freemarkerview and velocityview instances and return them to dispatcherservlet.

Q jasperreportsviewresolver. Jasperreportsviewresolver only looks for the jasperreport template file from the specified location based on the logical view name, and returns the specific child type view instance of abstractjasperreportsview, such as jasperreportscsvview or jasperreportshtmlview.

Q ttviewresolver. It is only responsible for finding and returning the view instance of the lateral tview type based on the logical view name.

Enabling viewresolver is as simple as using internalresourceviewresolver. The most basic method is to use the prefix attribute to specify the path of the template, and use the suffix attribute to specify the extension name of the template file. In this way, after obtaining the logical view name, the corresponding viewresolver can find the corresponding template file based on a URL such as [prefix] + viewname + [suffix, and construct the corresponding view instance and return. Take the use of velocityviewresolver as an example. For the use of several other viewresolvers, you can refer to the javadoc orProfessional Java Development with the Spring frameworkThe introduction of view chapters in this book. The following is an example of the configuration code for velocityviewresolver:

Class = "org. springframework. Web. servlet. View. Velocity. velocityviewresolver">

Currently, dispatcherservlet requests to the view will be taken over by velocityviewresolver. Velocity-viewresolver searches for the view in the specified directory based on the passed-in logic view name. VM-Type Velocity template file, and construct a velocityview instance and return it to dispatcherservlet for use. As we said, it is only responsible for finding a single view type corresponding to the velocity at the specified location, and does not return other view instances, such as the view instance corresponding to the freemarker view.

Note that you can refer to the additional information in the resourcebundle-viewresolver section later for details about the configuration required to use velocity as the view technology.

2. viewresolver for multiple view types

Using viewresolver for a single view type, we do not need to specify a clear ing relationship between the logical view name and a specific view, the corresponding viewresolver will automatically match the view Template under its jurisdiction at the specified location, and construct a specific view instance. Viewresolver is not applicable to multiple view types. To use viewresolver for multiple view types, We need to specify the ing between the logical view name and the specific view in a certain configuration method, which may cause cumbersome configuration. However, the advantage is that viewresolver for multiple view types can take into account the ing management of multiple view types. If you want to map your logical view name to internalresourceview, viewresolver for multiple view types can do this. If your logical view name is to be mapped to velocityview, viewresolver for multiple view types can also be used. Compared with the scenario where only single view type ing is supported, viewresolver for multiple view types is more flexible.

There are three main implementation classes for viewresolver for multiple view types: resourcebundleview-resolver, xmlviewresolver, and beannameviewresolver. The following describes their details.

Resourcebundleviewresolver. Resourcebundleviewresolver is built on resourcebundle. It inherits the international support capability of resourcebundle and is also the only viewresolver that provides international support for views in all viewresolver implementation classes. The logical name ing between the view managed by resourcebundleviewresolver and the specific view is stored in the properties file. The format conforms to the properties configuration format of Spring IoC container. Resourcebundleview-resolver loads the configuration information through propertiesbeandefinitionreader. Then, the operation based on the logical view name is actually simplified to the form of beanfactory. getbean (viewname) (of course, there are actually more things to do ).

Before using resourcebundleviewresolver, we must add it to the webapp-licationcontext of dispatcherservlet, as shown below:

Class = "org. springframework. Web. servlet. View. resourcebundleviewresolver">

If we do not specify where the properties configuration file is loaded, resourcebundleviewresolver loads the properties file with views as basename from the root path of classpath by default, such as views. properties and views_zh_cn.properties. To change the default loading behavior, use the setbasename (string) or setbasenames (string []) method.

The following is a typical properties configuration file used by resourcebundleviewresolver:

Viewtemplate. Class = org. springframework. Web. servlet. View. internalresourceview

Viewtemplate. (abstract) = true

Help/helpforsomething. (parent) = viewtemplate

Help/helpforsomething. url =/WEB-INF/JSP/help/helpforsomething. jsp

Hello. Class = org. springframework. Web. servlet. View. Velocity. velocityview

Hello. url = Cn/spring21/simplefx/resources/velocity/Hello. VM

# Other view definitions ......

The bean definition of a view has two attributes: class and URL. If you want to avoid specifying some common attributes for a view of the same type each time, you can also define a template declaration and reference the template declaration through parent. We have learned these features in the second part, haven't we?

Note: If you want to use a view rendered by a general template engine such as velocity or freemarker in resourcebundleviewresolver, you need to add the corresponding configuration in the webapplicationcontext so that the view rendering stage can obtain the support of the template engine. In fact, using velocityviewresolver or freemarker-viewresolver alone also requires the same configuration.

Take the configuration of the Velocity type view as an example. (the configuration of the freemarker type view is the same as that of the Velocity type view ). In the webapplicationcontext of the application, we add the configuration of org. springframework. Web. servlet. View. Velocity. velocityconfigurer as follows:

Class = "org. springframework. Web. servlet. View. Velocity. velocitycycler">

Value = "/WEB-INF/velocity-config.properties"/>

/Bean>

In this way, you can obtain a velocityengine Based on the configuration in the view rendering stage to merge the view template and data (merge) for final output of the view page.

The configuration content of the velocity-config.properties is exactly the content specific to velocity. You can refer to the relevant documentation of velocity to obtain configuration parameters. Here you can give a simple example, as shown below:

Resource. loader = classpath

Classpath. Resource. loader. Description = classpath resource Loader

Classpath. Resource. loader. Class =

Org. Apache. Velocity. runtime. Resource. loader. classpathresourceloader

Classpath. Resource. loader. Path =.

Velocimacro. Library =

Finally, the template files of velocity (or freemarker) are put into the classpath of the application as we specify the configuration content, instead of relying on the default file system loading behavior.

Xmlviewresolver. The major difference between xmlviewresolver and resourcebundleviewresolver is that they use different configuration file formats. Resourcebundleviewresolver configures the ing between logical view names and specific views according to the properties configuration format accepted by the Spring IoC container, xmlviewresolver loads the ing information according to the xml configuration file format accepted by the Spring IoC container. The configuration information is the same as resourcebundleviewresolver. If xmlviewresolver is used, the content is shown in the code list 24-28.

Code list 24-28 xmlviewresolver sample code for configuration

Class = "org. springframework. Web. servlet. View. internalresourceview"

Abstract = "true">

Class = "org. springframework. Web. servlet. View. Velocity. velocityview"

P: url = "cN/spring21/simplefx/resources/velocity/Hello. VM">

Xmlviewresolver loads/WEB-INF/views. XML as the configuration file by default. However, when adding xmlview-resolver to webapplicationcontext, we can change this default behavior as needed, for example:

Now, xmlviewresolver loads the configuration file named views. XML from the root path of classpath. As for other configurations, for example, velocitycycler required by velocity, because it has nothing to do with the viewresolver used, it is only related to whether velocity is used as the view technology, so it still needs to be added to webapplicationcontext as needed.

Note that xmlviewresolver does not support internationalization of views (i18n ). To support international views, use resourcebundleviewresolver.

Beannameviewresolver. Beannameviewresolver can be considered as the prototype or simplified version of xmlviewresolver. Using it, we can directly register the view instance to the specific webappli-cationcontext used by the current dispatcherservlet, instead of setting up another location like xmlviewresolver. However, beannameviewresolver is more used to quickly build application framework prototypes or small web applications. For normal Web applications based on Spring MVC, try to avoid adding the view configuration information that can be separated to the webapp-licationcontext of dispatcherservlet.

As for how to enable beannameviewresolver as viewresolver, I think you are better at it now, as shown below:

Class = "org. springframework. Web. servlet. View. beannameviewresolver"/>

For details about the configuration of a specific view, refer to xmlviewresolver.

In fact, as we can see, the three viewresolvers are essentially the same, but there are differences in the form of configuration. The final configuration information will be converted to the view instance managed in the Spring IoC container. beanname-viewresolver should be the initial implementation prototype!

24.4.2 viewresolver query sequence (chain of viewresolver)

Although we have always used an internalresourceviewresolver for view search in the previous example, this does not mean that each spring MVC-based Web application can only use one viewresolver. In fact, dispatcher-servlet can not only accept multiple handlermapping to process the ing between Web requests and specific handler, but also accept multiple viewresolvers to process view searches.

During dispatcherservlet initialization, viewresolver defined in webapplicationcontext is scanned Based on the type. If multiple viewresolver definitions are found, dispatcherservlet sorts the viewresolver based on their priorities. Then, when you need to find a specific view instance based on the logical view name, the viewresolver will be traversed in the sorted order. If any viewresolver returns a non-empty view instance during this period, the current search will end. If dispatcherservlet fails to find any viewresolver definition in the current webapplicationcontext, it uses internalresourceviewresolver as the default viewresolver.

Viewresolver uses the ordered interface as the standard to specify the priority, which has become a convention for setting the priority in the Spring framework. Suppose we want to use resourcebundleviewresolver to find the logical view name to a specific view instance. If not, we will seek help from internalresourceviewresolver. We can add the following configuration content to the webapplicationcontext of Dispatcher-servlet:

Class = "org. springframework. Web. servlet. View. resourcebundleviewresolver">

Class = "org. springframework. Web. servlet. View. internalresourceviewresolver">

The ID or name attribute value corresponding to the bean definition of the corresponding viewresolver is arbitrary, and dispatcherservlet obtains the viewresolver according to the type. If the order value is not specified for a viewresolver, the default value is integer. Max _ value, which corresponds to the lowest priority.

If multiple viewresolvers are specified for dispatcherservlet, do not give the internalresour-ceviewresolver and other urlbasedviewresolver subclass a high priority, because these viewresolvers cannot find the corresponding view, it will not return NULL to give us the chance to poll the next viewresolver. In this way, the other viewresolver we specify is actually a virtual setting. A reasonable solution is to give resourcebundleview-resolver or xmlviewresolver the ability to return NULL to indicate that the viewresolver of the corresponding view cannot be found with a higher priority, instead, add internalresourceviewresolver (or viewresolver with similar behavior) as the lowest priority viewresolver to serve as the backup lookup object of dispatcherservlet.

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.