InternalResourceViewResolver in Spring MVC

In the Spring MVC as I mentioned in this tutorial, the last step of processing the request, DispatcherServlet selects the View Template and passes the Model data so that the View Template can handle rendering the interface and return it to the DispatcherServlet. The View Template will be the implementations of the ViewResolver interface, and they will determine how the rendering of the interface will occur based on the view name we return from the controller. Spring MVC has many implementations of the ViewResolver interface, one of which we have InternalResourceViewResolver. In this tutorial, let’s learn together about InternalResourceViewResolver!

First, I will create a Spring Legacy Project in the Spring Tool Suite as an example:

InternalResourceViewResolver in Spring MVC

Someone who does not know how to create this, can refer to this tutorial.

The properties in the pom.xml file, I will edit the version of the libraries, the frameworks as follows:

To run this project, I will use the Maven Jetty Plugin as follows:

OK, let’s go into the main thread of this tutorial.



By default, when we create a Spring MVC project using the Spring Legacy Project in the Spring Tool Suite, this project will support the InternalResourceViewResolver. If you open the servlet-context.xml file located in the /src/main/WEB-INF/spring/appServlet directory, you will see a bean declaration for the InternalResourceViewResolver as follows:

InternalResourceViewResolver maps the view name we return from the controller with a filename in the specified directory.

In the above bean declaration, the InternalResourceViewResolver will map all view names to files with the extension .jsp located in the /src/main/WEB-INF/views directory to render the interface to us.

For our example, in the HomeController class located in the com.huongdanjava.springmvc package, we have defined the request “/” with the view name returned in the home() method as “home”.

With such a return statement, the InternalResourceViewResolver loads the “WEB-INF /views/home.jsp” file to render the interface.

Here are some examples of how to map a view with a view:

  • home -> /WEB-INF/views/home.jsp
  • admin / login -> /WEB-INF/views/admin/login.jsp

By default, the InternalResourceViewResolver will resolve our view name into a view object of the JstlView class if the JSTL library is in the classpath of the project. And in the internal bean declaration of InternalResourceViewResolver we also have to declare a property “viewClass” as follows:

But since the default is JstlView, we do not need to declare the “viewClass” property like that.

If you use other ViewResolver objects then you need to declare the viewClass.

Result:

InternalResourceViewResolver in Spring MVC

 

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment