Home  >  Article  >  Java  >  What is the role of view resolver in Spring MVC?

What is the role of view resolver in Spring MVC?

PHPz
PHPzOriginal
2024-04-17 16:54:01278browse

View resolvers in Spring MVC convert application model objects into user-visible views, such as JSP, HTML, or PDF. When the controller returns a logical view name, the view resolver parses it into an actual view and passes it to the view renderer for generation. For example, InternalResourceViewResolver uses "/WEB-INF/jsp/" as the prefix for JSP files and ".jsp" as the suffix.

Spring MVC 中视图解析器的作用是什么?

The role of the view resolver in Spring MVC

In Spring MVC, the view resolver plays a role in processing user requests vital role. Its role is to convert the model objects returned by the application into a user-visible view, such as a JSP, HTML, or PDF file.

Process

  1. When a controller handles a request, it will return a logical view name, such as "home".
  2. Spring MVC passes the logical view name to the view resolver.
  3. The view resolver resolves the actual view based on the logical view name. It uses specific strategies to do this, such as mapping logical view names to actual paths or file extensions.
  4. The view resolver passes the actual view to a view renderer, such as a JSP or PDF engine.
  5. The renderer generates the visual page that the user finally sees.

Practical case

The following example demonstrates how to configure Spring MVC to use the InternalResourceViewResolver view resolver:

@Configuration
public class MvcConfig {

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

In this configuration, The InternalResourceViewResolver view resolver will use "/WEB-INF/jsp/" as the prefix for JSP files and ".jsp" as the suffix.

When the controller returns a logical view name "home", the view resolver will parse the actual view as "/WEB-INF/jsp/home.jsp" and pass it to the JSP engine for rendering.

The above is the detailed content of What is the role of view resolver in Spring MVC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn