What is ViewResolver in Spring MVC?

What is ViewResolver in Spring MVC?

The View Resolver in Spring MVC is an interface that helps to resolve the view name to an actual view object, which is then rendered to the user. It maps view names to actual view objects, allowing the controller to return a logical view name rather than a direct view object.

Role of ViewResolver:

  • Decoupling Logic: Separates the controller from the view technology, enabling the use of different view technologies (e.g., JSP, Thymeleaf).
  • Flexibility: Allows configuring different view resolvers for different view technologies.
  •  Configuration: Typically configured in the Spring configuration file or Java-based configuration.

Spring provides several implementations of the `View Resolver` interface, including:

  • InternalResourceView Resolver: Used for JSP-based views.
  • ThymeleafViewResolver: Used for Thymeleaf templates.
  • FreeMarkerViewResolver: Used for FreeMarker templates.
  • VelocityViewResolver: Used for Velocity templates.

ViewResolver

Java Example Using JSP and InternalResourceView Resolver

Project Structure
```
src
 └── main
     └── java
         └── com
             └── example
                 └── config
                     └── WebConfig.java
                 └── controller
                     └── HomeController.java
     └── resources
         └── application.properties
     └── webapp
         └── WEB-INF
             └── views
                 └── home.jsp
     └── web.xml
```

Maven Dependencies (pom.xml)
 2. Maven Dependencies (pom.xml)
```xml
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
```

Web Configuration (WebConfig.java)
 3. Web Configuration (WebConfig.java)
```java
package com.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller")
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }
}
```

Controller (HomeController.java)
4. Controller (HomeController.java)
```java
package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Spring MVC!");
        return "home"; // returns the view name "home"
    }
}
```

View (home.jsp)
 5. View (home.jsp)
```jsp
<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>
```

web.xml Configuration
6. web.xml Configuration
```xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 
         version="4.0">
    
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
```

Explanation of the Example:

1. DispatcherServlet Configuration (web.xml):

   The `DispatcherServlet` is configured to intercept all incoming requests and is initialized with the Spring configuration file located at `/WEB-INF/spring/dispatcher-config.xml`.

2. WebConfig.java:

  •  This Java-based configuration class enables Spring MVC (`@EnableWebMvc`) and specifies component scanning for the package containing controllers (`@ComponentScan`).
  •  Configures the `InternalResourceView Resolver` to resolve view names to JSP files located in `/WEB-INF/views/` and with a `.jsp` suffix.

3. HomeController.java:

  • A simple controller that handles HTTP GET requests to the root URL (`/`).
  •  Adds a message to the model and returns the view name (`home`).

4. home.jsp:

   The JSP file that renders the model data. It displays the message set by the controller.

Homepage

Readmore