Saturday, October 27, 2018

What is the role of InternalResourceViewResolver in Spring MVC?

Earlier, I have explained to you about how Spring MVC works internally and how it process HTTP request coming to your web application. One of the important parts of that processing was view resolution, which is handled by the ViewResolver interface. In this article, you'll learn more about it by explaining the InternalResourceViewResolver class. The InternalResourceViewResolver is an implementation of ViewResolver in Spring MVC framework which resolves logical view name e.g. "hello" to internal physical resources e.g. Servlet and JSP files e.g. jsp files placed under WEB-INF folder. It is a subclass of UrlBasedViewResolver, which uses "prefix" and "suffix" to convert a logical view name returned from 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 WEB-INF directory, to hide them from direct access (e.g. via a manually entered URL). If we put then inside 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 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 configure InternalResorveViewResolver in Spring MVC

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


Configuring ViewResolver using XML in Spring
Here is some XML snippet to configure a view resolve 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" /> 


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 offers 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 5: Beginner to Guru, one of the comprehensive and hands-on course to learn modern Spring.

What is the role of InternalResourceViewResolver do in Spring MVC?




Important points about InteralResourceViewResolver in Spring MVC

Here are some of the important things to know about this useful class from 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 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 e.g. currency and dates. It's 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 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 return 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's has also explained about different types of view resolvers in Spring on his classic course  Introduction to Spring MVC 4, if you have a Pluarlsight membership then that is one of the best resources.

What does the InternalResourceViewResolver do in Spring MVC?


Pluralsight is like NetFlix for Software developers.  It has more than 5000+ good quality courses on all latest topics. Since we programmers have to learn new things every day, there membership cost around $29 monthly or $299 annually (14%saving),  an investment of $299 USD annually on your learning is not bad.

Btw, they also offer a 10-day free trial without any obligation which allows you to watch 200 hours of content. You can watch this course for free by signing for that trial.


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 which 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 controller as long as logical view name is same.


That's all about what does InternalResourceViewResolver do in Spring MVC or what is the role of InternalResourceViewResolver. It's one of the useful class from Spring MVC and as a Java Spring developer, you should be familiar with it. The concept of view resolution in Spring MVC is also very important from both Spring interview as well as 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.

Further Reading
Spring Framework 5: Beginner to Guru
Spring Master Class - Beginner to Expert
5 Free Spring Core and Spring Boot Courses for Java Developers


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)
  • 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)

Thanks for reading this article. If you like this article then please share 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.

No comments :

Post a Comment