Wednesday, March 22, 2023

How View Resolver works in Spring MVC? [InternalResourceViewResolver Example]

Hello guys, if you are wondering what is view resolver in Spring MVC and what role InternalViewResolver class plays in Spring MVC then you have come to the right place. Earlier, I have explained to you how Spring MVC works internally and how it processes HTTP requests coming to your web application. One of the important parts of that processing was resolving views, which is handled by the ViewResolver interface, which is the V part of MVC. They are responsible for returning correct views to the client, both in the Spring MVC application as well as on REST APIs. In this article, you'll learn more about view resolvers in Spring MVC by explaining the InternalResourceViewResolver class. 

The InternalResourceViewResolver is an implementation of the ViewResolver interface in the Spring MVC framework which resolves logical view names like "hello" to internal physical resources like Servlet and JSP files like jsp files placed under the WEB-INF folder.

It is also a subclass of UrlBasedViewResolver, which uses "prefix" and "suffix" to convert a logical view name returned from the Spring controller to map to actual, physical views.

For example, if a user tries to access /home URL and HomeController returns "home" then DispatcherServlet will consult InternalResourceViewResolver and it will use prefix and suffix to find the actual physical view which is integral to a web application.

Like, if prefix is "/WEB-INF/views/" and suffix is ".jsp" then "home" will be resolved to "/WEB-INF/home.jsp" by InternalResourceViewResolver.

It's also a  best practice to put all JSP files inside the WEB-INF directory, to hide them from direct access (e.g. via a manually entered URL). If we put them inside the WEB-INF directory then only controllers will be able to access them.

Even though it's not mandatory that View can only be JSP, it can be JSON also, for example for REST web services, but for the sake of simplicity, we'll take the example of JSP as a view in this article. If you are interested in view resolution in REST web services, you can take a look at REST with Spring MasterClass by Eugen Paraschiv of Baeldung.



How to use InternalResourceViewResolver in Spring MVC?

Let's first start with the configuration of view resolvers in Spring MVC. You can configure this ViewResolver either using Java Configuration or XML configuration as shown below:

1. Configuring ViewResolver using XML in Spring

Here is some XML snippet to configure a view resolver in Spring, you can use this if you are working on a Spring project which is using XML based confirmation:

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


2. Configuring ViewResolver using Java Configuration

From Spring 3.0 you can also configure view resolver using Java i.e. without XML. You can use the following code to configure the internal resource view resolver in your spring project:

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

    return irv;

  }

You can see that both the XML and Java offer a simple approach to configure internal resource view resolver in Spring. Though, I suggest you use Java Configuration which is modern and now becoming the standard way to configure Spring application. If you are new to Java Configuration, I suggest you take a look at Spring Framework: Beginner to Guru, one of the comprehensive and hands-on courses to learn modern Spring.

what is view resolvers in spring mvc




Important points about InteralResourceViewResolver in Spring MVC

Here are some of the important things to know about this useful class from the Spring MVC framework. This will help you to understand the flow of your project better:

1) When chaining ViewResolvers, an InternalResourceViewResolver always needs to be last, as it will attempt to resolve any view name, no matter whether the underlying resource actually exists.

2) The InternalResourceViewResolver is also the default view resolver of DispatcherServlet class, which acts as the front controller in the Spring MVC framework.

3) By default, InternalResourceViewResolver returns InternalResourceView (i.e. Servlets and JSP) but it can be configured to return JstlView by using the viewClass attribute as shown below:

/**
   * Sets the default setViewClass view class to requiredViewClass: by default
   * InternalResourceView, or JstlView if the JSTL API is present.
   */
  public InternalResourceViewResolver() {
    Class viewClass = requiredViewClass();
    if (viewClass.equals(InternalResourceView.class) && jstlPresent) {
      viewClass = JstlView.class;
    }
    setViewClass(viewClass);
  }

  /**
   * This resolver requires InternalResourceView.
   */
  @Override
  protected Class requiredViewClass() {
    return InternalResourceView.class;
  }


The advantage of using JstlView is that JSTL tags will get the Locale and any message source configured in Spring. This is particularly important when you are using JSTL tags for formatting for displaying messages.


JSTL's formatting tags need a Locale to properly format locale-specific values like currency and dates. Its message tags can use a Spring message source and a Locale to properly choose the message to render in HTML depending upon Locale.

You can further see Spring in Action 5th Edition by Craig Walls for more details on JstlView class. The book is a gem and my favorite to learn Spring in detail. It is now also updated to cover Spring 5.0 changes.

how does view resolver work in Spring MVC framework



4. The InteralResourceViewResolver is one of the several built-in view resolvers provided by the Spring framework, some of the most useful ones are listed below:
  • BeanNameViewResolver - resolves views as beans in the Spring application context whose ID is the same as the view name. For example, if you have a bean with id = "home" and a controller returns a logical view name as "home" then this bean will be resolved by BeanNameViewResolver.
  • FreeMarkerViewResolver - resolver views as FreeMarker templates
  • JasperReportsViewResolver - resolves views as JasperReports definitions
  • XsltViewResolver - resolves views to be rendered as the result of an XSLT transformation. 
Bryan Hassen has also explained about different types of view resolvers in Spring on his classic course Spring Framework: Spring MVC Fundamentals if you have a Pluralsight membership then that is one of the best resources.





5. The most important benefit of using ViewResolver in Spring MVC is that it decouples request-handling logic in the controller from the view-rendering of a view. In short, the controller doesn't know anything about which view technology is used to render the view.

It just returns a logical name that could resolve to a JSP, FreeMarker template, Apache tiles, or any other view technology. It also means you can change the view layer without changing the controller as long as the logical view name is the same.

The concept of view resolution in Spring MVC is also very important from both the Spring interview as well as the Spring certification point of view. If you are preparing for Spring certification, I suggest you go through some questions shared by David Mayer's Spring Mock exams to test your knowledge of view resolution concept in Spring MVC.

That's all about what is view resolvers in spring, how they work, and what is the role of InternalResourceViewResolver in Spring MVC or what is the role of InternalResourceViewResolver.  View resolution is one of the core MVC concepts and Spring MVC also works the same. It's one of the useful classes from Spring MVC and as a Java Spring developer, you should be familiar with it. 


Other Spring related articles you may like to explore this blog
  • 23 Spring MVC Interview questions for 2 to 3 years experienced (list)
  • How Spring MVC works internally? (answer)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • How to enable Spring security in Java application? (answer)
  • Top 7 Courses to learn Microservices in Java (courses)
  • 10 Free Courses to learn Spring Framework for Beginners (free courses)
  • Does Spring certification help in Job and Career? (article)
  • How to prepare for Spring Certification? (guide)
  • 3 Best Practices Java Developers Can learn from Spring (article)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Spring and Hibernate online courses for Java developers (list)
  • 15 Spring Boot Interview Questions for Java Developers (questions)
  • Top 5 Courses to Learn and Master Spring Cloud (courses)
  • 5 Courses to Learn Spring Security in depth (courses)
  • Top 5 Spring Boot Annotations Java Developers should know (read)
  • @SpringBootApplication vs @EnableAutoConfiguration? (answer)
  • 5 Spring Books Experienced Java Developer Should Read (books)
  • 10 Advanced Spring Boot Courses for Java developers (courses)
  • 10 Free Courses to learn Spring Boot in-depth (free courses
  • Top 5 Frameworks Java Developer Should Know (frameworks)
  • 7 Best Spring Courses for Beginners and Experienced (courses)
  • 10 Spring MVC annotations Java developer should learn (annotations)
  • Top 5 Spring Cloud annotations Java programmer should learn (cloud)
  • 5 Courses to learn Spring Cloud for Beginners (courses)

Thanks for reading this article. If you like this explanation of view resolvers in spring and internal view resolve example then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment and I'll try to answer it as soon as possible.

P. S. - If you want to learn how to develop RESTful Web Services using Spring Framework, check out Eugen Paraschiv's REST with Spring course. He has recently launched the certification version of the course, which is full of exercises and examples to further cement the real world concepts you will learn from the course.

1 comment :

Jems22swift said...

I think you can use Spring Boot.
In spring boot you can make a model, repository, service, controller, and view.
Model is a representation of a table in database, repository contain all of database command and service just consume the repository.
So here the flow :
1. View make a request to controller
2. Controller call a service
3. Service do a query in repository
4. The result of the query will be transform into model
5. Service return back the result the controller
6. Controller send the response to the view

Post a Comment