Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

ViewResolver in Spring MVC

In Spring MVC, the ViewResolver is responsible for resolving views based on the logical view name returned by the controller. It maps that logical name to a physical view, whether it be a JSP, Thymeleaf template, or any other supported view technology.

There are several types of ViewResolver in Spring, but the most commonly used are:

  • InternalResourceViewResolver: This is used to resolve JSPs. Here's an example of how to configure it:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

Or using Java configuration:

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

If a controller returns a view name "home", the InternalResourceViewResolver will look for /WEB-INF/views/home.jsp.

  • ThymeleafViewResolver: If you're using Thymeleaf templates:
<bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />
</bean>

Or using Java configuration:

@Bean
public ThymeleafViewResolver viewResolver(ITemplateEngine templateEngine) {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(templateEngine);
    return resolver;
}
  • XmlViewResolver: This is used to resolve XML configurations for views.

  • JstlView and TilesView: For projects using JSTL or Apache Tiles respectively.

  • ContentNegotiatingViewResolver: This allows you to determine the view technology based on the requested content type. For instance, if a client requests JSON, this resolver can be set up to return a view that generates JSON.

The beauty of Spring's view resolver mechanism is that you can chain multiple resolvers together. When a view name is returned, each resolver is consulted in turn until one provides a match.

Example:

Say you have both JSP and Thymeleaf templates in your application, and you want to use both. You could set up both an InternalResourceViewResolver and a ThymeleafViewResolver. The order of these beans would determine which technology is given priority when resolving a view.

Remember, for these configurations to work, you need the appropriate dependencies in your project. For example, for Thymeleaf, you would need Thymeleaf's Spring integration library.

  1. Configuring ViewResolver in Spring MVC:

    In Spring MVC, ViewResolver is responsible for resolving views based on logical view names returned by controllers. It can be configured in the Spring configuration file.

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

    Here, the InternalResourceViewResolver is configured with a prefix and suffix for JSP views.

  2. InternalResourceViewResolver in Spring example:

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

    This configuration sets up an InternalResourceViewResolver to resolve JSP views located in the "/WEB-INF/views/" directory.

  3. Spring MVC ViewResolver XML configuration:

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

    The XML configuration demonstrates setting up an InternalResourceViewResolver for JSP views.

  4. Multiple ViewResolvers in Spring MVC:

    <!-- applicationContext.xml -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="location" value="/WEB-INF/views/views.xml" />
    </bean>
    

    This example configures both InternalResourceViewResolver and XmlViewResolver. The order of declaration matters as it defines the order in which resolvers are applied.

  5. Thymeleaf ViewResolver in Spring MVC:

    <!-- applicationContext.xml -->
    <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
        <property name="characterEncoding" value="UTF-8" />
    </bean>
    
    <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
    </bean>
    
    <bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/WEB-INF/templates/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
    </bean>
    

    This configuration sets up a ThymeleafViewResolver for resolving Thymeleaf views.

  6. Mapping views with ViewResolver in Spring:

    Views can be mapped to logical names in controller methods:

    @Controller
    public class MyController {
    
        @GetMapping("/showPage")
        public String showPage(Model model) {
            model.addAttribute("message", "Hello, Spring MVC!");
            return "my-page";
        }
    }
    

    Here, "my-page" is a logical view name.

  7. Custom ViewResolver implementation in Spring MVC:

    Implement a custom ViewResolver:

    public class MyViewResolver implements ViewResolver {
    
        @Override
        public View resolveViewName(String viewName, Locale locale) throws Exception {
            // Custom view resolution logic
            return new MyView();
        }
    }
    

    Register the custom resolver in the Spring configuration.

  8. Resolving views with JSP in Spring MVC:

    In Spring MVC, JSP views can be resolved using InternalResourceViewResolver. Controller returns logical view names.

    @Controller
    public class MyController {
    
        @GetMapping("/showJspPage")
        public String showJspPage(Model model) {
            model.addAttribute("message", "Hello, JSP!");
            return "jsp-page";
        }
    }
    
  9. ViewResolver vs ModelAndView in Spring MVC:

    • ViewResolver: Resolves logical view names to actual view implementations. Configured in the Spring context.
    • ModelAndView: Represents a model and a view. Allows specifying both the logical view name and model data in a controller method.
    @Controller
    public class MyController {
    
        @GetMapping("/showPage")
        public ModelAndView showPage() {
            ModelAndView modelAndView = new ModelAndView("my-page");
            modelAndView.addObject("message", "Hello, ModelAndView!");
            return modelAndView;
        }
    }
    

    Here, "my-page" is the logical view name, and "message" is added to the model.