Open In App
Related Articles

ViewResolver in Spring MVC

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Spring MVC is a Web MVC Framework for building web applications. In generic all MVC frameworks provide a way of working with views. Spring does that via the ViewResolvers, which enables you to render models in the browser without tying the implementation to specific view technology. Now let’s understand ViewResolver with an example project in STS. 

The Spring MVC framework is comprised of the following components:

  1. Model: A model can be an object or collection of objects which basically contains the data of the application.
  2. View: A view is used for displaying the information to the user in a specific format. Spring supports various technologies like freemarker, velocity, and thymeleaf.
  3. Controller: It contains the logical part of the application. @Controller annotation is used to mark that class as controller.
  4. Front Controller: It remains responsible for managing the flow of the web application. DispatcherServlet acts as a front controller in Spring MVC.

Requirements: Prior to it, certain requirements are needed that are as follows:  

  1. Eclipse (EE version)/STS IDE
  2. Spring JAR Files
  3. Tomcat Apache latest version

Implementation: Project

It is illustrated below step by step as follows:

Note: We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS in your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? 

Step 1: Create a Dynamic Web Project in your STS IDE for which one should be well versed in how to create a Dynamic Web Project in Spring Tool Suite?

Step 2: Download the spring JARs file and go to the src > main > webapp > WEB-INF > lib folder and past these JAR files. 

Step 3: Configure Apache Tomcat Server and configure the Tomcat Server with the application. 

Configuring ‘Dispatcher Servlet’

Do go through dispatcher Servlet in Spring and read more about Dispatcher Servlet which is a very very important concept to understand. Now we are going to configure Dispatcher Servlet with our Spring MVC application. 

Step 4: Go to the src > main > webapp > WEB-INF > web.xml file.

File: web.xml

XML

<?xml version="1.0" encoding="UTF-8"?>
               xmlns="http://xmlns.jcp.org/xml/ns/javaee"
               xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
       id="WebApp_ID" version="4.0">
       <display-name>springmvc-view-resolver</display-name>
       <welcome-file-list>
              <welcome-file>index.html</welcome-file>
              <welcome-file>index.jsp</welcome-file>
              <welcome-file>index.htm</welcome-file>
              <welcome-file>default.html</welcome-file>
              <welcome-file>default.jsp</welcome-file>
              <welcome-file>default.htm</welcome-file>
       </welcome-file-list>
 
       <absolute-ordering />
 
       <servlet>
              <!-- Provide a Servlet Name -->
              <servlet-name>viewresolver-dispatcher</servlet-name>
              <!-- Provide a fully qualified path to the DispatcherServlet class -->
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <load-on-startup>1</load-on-startup>
       </servlet>
 
       <servlet-mapping>
              <!-- Provide a Servlet Name that you want to map -->
              <servlet-name>viewresolver-dispatcher</servlet-name>
              <!-- Provide a url pattern -->
              <url-pattern>/demo.com/*</url-pattern>
       </servlet-mapping>
 
</web-app>

                    


Step 5: Now go to the  src > main > webapp > WEB-INF and create an XML file. Actually, this is a Spring Configuration file like the beans.xml file. And the name of the file must be in this format.

YourServletName-servlet.xml  

For example, for this project, the name of the file must be

viewresolver-dispatcher-servlet.xml 

So either you can create a Spring Configuration File or you can just create a simple XML file and add the below lines of code inside that file.

File: viewresolver-dispatcher-servlet.xml

XML

<?xml version="1.0" encoding="UTF-8"?>
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   
  <!-- This Line is used for scanning all the packages that have controller classes -->
  <context:component-scan base-package="com.demo.controllers"></context:component-scan>
 
</beans>

                    

Creating ‘Spring MVC Controller’

Step 6: Now, let’s create some controllers. Go to the src/main/java and create a new controllers package (For ex. com.demo.controllers) as per your choice. And inside that create a Java class and name the class as DemoController. Now how to tell the Spring that this is our controller class. So the way we are going to tell the Spring is by marking it with a @Controller annotation.

@Controller
public class DemoController {}

Note: Spring will automatically initialize the class having a @Controller annotation and register that class with the spring container.

Now let us create a simple method inside the Controller class and use the @RequestMapping annotation before the method something like this.

// Annotation 
@RequestMapping("/hello")

// Method 
public String helloWorld() 
{
    return "";
}

Now in the return statement, we have to return some views (web pages), so whenever the endpoint ‘/hello’ is invoked we can see our result on the web page. So let’s create our first View.

Creating ‘View’

Go to the src > main > webapp > WEB-INF > right-click > New > Folder and name the folder as views. Then views > right-click > New > JSP File and name your first view. Here we have named it a demo.jsp file. Below is the code for the demo.jsp file. We have created a simple web page inside that file. 

File: demo.jsp

HTML

<!DOCTYPE html>
<html>
<body bgcolor="green">
    <h1>Hello GeeksforGeeks!</h1>
</body>
</html>

                    

Now go to the DemoController class and inside the helloWorld() method we have to return a value something like this.

return "/WEB-INF/views/demo.jsp";

We have just been given the path for our view.

File: DemoController.java 

Java

// Java Program to Illustrate DemoController Class
 
package com.demo.controllers;
 
// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
// Class
@Controller
public class DemoController {
 
    // Method
    @RequestMapping("/hello") public String helloWorld()
    {
        return "/WEB-INF/views/demo.jsp";
    }
}

                    

Running ‘Spring MVC Application’

Step 7: To run our Spring MVC Application right-click on your project > Run As > Run on Server. And run your application as shown in the below image as depicted below as follows:  

After that use the following URL to run your controller

http://localhost:8080/springmvc-view-resolver/demo.com/hello

Output:

Output

 

So what’s the problem with the above project? Just go to the DemoController.java file again and the problem lies in this line of code:

return "/WEB-INF/views/demo.jsp";

So the scenario is, suppose someone tells us to create or move this demo.jsp file inside another directory and here we have to change the path again which is not a standard coding practice. The problem here is, that we have provided a fully qualified path in our controller handler method which makes our application tightly coupled and the solution for this problem is ViewResolver. For changing the path many times you should go to your spring configuration file (here is: viewresolver-dispatcher-servlet.xml) and there you can modify these things. Now let’s understand how ViewResolver solves this problem.  

Here is this line, /WEB-INF/views/demo.jsp, sometimes a scenario exists, when somebody wants to change either WEB-INF/views (the path) or .jsp (the extension like .html), the name must be the same. 

 

And we call them prefixes and suffixes accordingly. Now let’s understand this thing in the following code but before that let’s learn about ViewResolver a little bit. In the Spring framework, there is plenty of ViewResolver available. But in this project, we are going to use InternalResourceViewResolver. Now let us jump to the coding part. 

Step 8: Go to the DemoController.java file and modify the code as shown in the below snippet. 

File: Modified DemoController.java 

Java

// Java Program to Illustrate DemoController Class
 
package com.demo.controllers;
 
// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
// Class
@Controller
public class DemoController {
 
    // Method
    @RequestMapping("/hello") public String helloWorld()
    {
 
        // Just return the page name
        // No Path, no extension
        return "demo";
    }
}

                    

Here we have only returned the page name, nothing else. 

Note: The return file name and the View name must be same because we are returning that web page from the controller handler method. 

Configure ViewResolver inside the Spring Configuration File (i.e. viewresolver-dispatcher-servlet.xml)

Step 9: Modify the viewresolver-dispatcher-servlet.xml and add the below lines of code as follows: 

<bean id = 'viewResolver' class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

This is the thing we have discussed above and it’s completely the concept of Setter Based Dependency Injection in the spring framework.

File: viewresolver-dispatcher-servlet.xml

XML

<?xml version="1.0" encoding="UTF-8"?>
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   
  <!-- This Line is used for scanning all the packages that have controller classes -->
  <context:component-scan base-package="com.demo.controllers"></context:component-scan>
   
  <!-- Configure ViewResolver -->
  <bean id = 'viewResolver' class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
  </bean>
 
</beans>

                    

Now inside this “value” property, you can change according to the requirements as many times as you want. Now run your spring application and the output will be as follows.

Output:

Output

 



Last Updated : 02 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads