How to Resolve View
In Spring MVC, InternalResourceViewResolver allow us to add some predefined prefix and suffix to the view name (prefix + view name + suffix), and generate the final view page URL as below.
prefix + logical view name + suffix = /WEB-INF/view/MyPage.jsp
Configuring InternalResourceViewResolver in Spring MVC
To configure InternalResourceViewResolver, you can declare a bean of this type in the web application context either with XML configuration or with Java Configuration as below.
In XML Configuration
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="suffix" value=".jsp"/> <property name="prefix" value="/WEB-INF/view/"/> </bean>
In Java Configuration
@Bean public ViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); return viewResolver; }
InternalResourceViewResolver resolves view names into view objects of type JstlView by default if the JSTL library jstl.jar available into classpath of the application. So you do not need to explicitly add the viewClass property. But you can override this property by adding viewClass property of InternalResourceViewResolver. In below code we add other view class TilesView instead of JstlView class based on tiles.
In XML Configuration
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="suffix" value=".jsp"/> <property name="prefix" value="/WEB-INF/view/"/> <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" /> </bean>
In Java Configuration
@Bean public ViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/view/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(TilesView.class); return viewResolver; }
What’s internal resource views?
In Spring MVC or any web application, for good practice, it’s always recommended to put the entire views or JSP files under “WEB-INF” folder, to protect it from direct access via manual entered URL. Those views under “WEB-INF” folder are named as internal resource views, as it’s only accessible by the servlet or Spring’s controllers class.
Summary
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…