Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring MVC - Multiple Resolver Mapping
Next article icon

Spring MVC - Multiple Resolver Mapping

Last Updated : 24 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring MVC Framework provides the feature of View Resolver through which you can map a view to its respective view and render the model in your browser. The View Resolver eliminates the use of view technologies like Velocity and JSP. There are many view resolvers available in spring-like InternalResourceViewResolver, XmlViewResolver, ResourceBundleViewResolver, etc all having a different way to handle view. Spring MVC also supports multiple view resolvers to rely on others if one fails, in case of multiple view resolvers we need to mention the order or the priority of those view resolver that we want them to work according to.

Implementation: Here we 'will be creating a simple Spring MVC project and implementing multiple view resolvers for a single view page.

Note: Spring MVC is required as a pre-requisite

Steps to Create Project

Step 1: Create a maven project using create a new project, now add maven-archetype-webapp to your project as we are creating a web application. 

Step 2: Add the group Id, Artifact Id and click on finish.

The project would get created with a pom.xml configuration file, the structure of your project would look something like this:

The pom.xml configuration file defines the dependencies that maven gets and manages for your project. After creating the project our pom.xml looks like this below as follows:

File: pom.xml

XML
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">   <modelVersion>4.0.0</modelVersion>   <groupId>com.mkyong.common</groupId>   <artifactId>SpringMVC</artifactId>   <packaging>war</packaging>   <version>1.0-SNAPSHOT</version>   <name>SpringMVC Maven Webapp</name>   <url>http://maven.apache.org</url>   <dependencies>     <dependency>       <groupId>junit</groupId>       <artifactId>junit</artifactId>       <version>3.8.1</version>       <scope>test</scope>     </dependency>          <!-- Spring framework -->      <dependency>         <groupId>org.springframework</groupId>         <artifactId>spring</artifactId>         <version>2.5.6</version>     </dependency>       <!-- Spring MVC framework -->      <dependency>         <groupId>org.springframework</groupId>         <artifactId>spring-webmvc</artifactId>         <version>2.5.6</version>     </dependency>          <!-- JSTL -->      <dependency>         <groupId>javax.servlet</groupId>         <artifactId>jstl</artifactId>         <version>1.1.2</version>     </dependency>          <dependency>         <groupId>taglibs</groupId>         <artifactId>standard</artifactId>         <version>1.1.2</version>     </dependency>     </dependencies>   <build>     <finalName>SpringMVC</finalName>   </build> </project> 

The web.xml file defines mapping with different URLs and servlets to handle requests for those URLs. In this configuration file, we have used listener for application startup, configured servlet, and added a servlet-mapping to map the URL.

File: web.xml

XML
<web-app id="WebApp_ID" version="2.4"      xmlns="http://java.sun.com/xml/ns/j2ee"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">    <display-name>Spring MVC</display-name>      <listener>     <listener-class>       org.springframework.web.context.ContextLoaderListener     </listener-class>   </listener>      <servlet>       <servlet-name>gfg</servlet-name>     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     <load-on-startup>1</load-on-startup>   </servlet>      <servlet-mapping>      <servlet-name>gfg</servlet-name>     <url-pattern>*.htm</url-pattern>   </servlet-mapping>    <context-param>     <param-name>contextConfigLocation</param-name>     <param-value>/WEB-INF/gfg-servlet.xml</param-value>   </context-param>    </web-app> 

The gfg-servlet.xml located in  "/src/main/webapp/WEB-INF/gfg.servlet.xml" is the files where we define beans and mapping for our project. This is the file where we have defined the view Resolvers. The InternalResolverViewResolver is a subclass of UrlBasedViewResolver that supports InternalResourceView. The XmlViewResolver supports files written in xml.

File: gfg-servlet.xml

XML
<beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://www.springframework.org/schema/beans      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">      <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />     <bean class="com.gfg.controller.WelcomeController" />    <bean id="viewResolver"           class="org.springframework.web.servlet.view.InternalResourceViewResolver" >           <property name="prefix">               <value>/WEB-INF/pages/</value>            </property>           <property name="suffix">              <value>.jsp</value>           </property>           <property name="order" value="1" />     </bean>      <bean class="org.springframework.web.servlet.view.XmlViewResolver">        <property name="location">            <value>/WEB-INF/spring-views.xml</value>        </property>        <property name="order" value="0" />     </bean>        <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">         <property name="mappings">             <props>                 <prop key="/welcomePage.htm">welomecontroller</prop>             </props>         </property>     </bean>          <bean id="welcomeController"          class="org.springframework.web.servlet.mvc.ParameterizableViewController">         <property name="viewName" value="welcomepage" />     </bean>       </beans> 

The spring-views.xml page is the xml based view page for our XmlViewResolver to handle, this page defines the bean for welcomepage.

File: spring-views.xml

XML
<beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://www.springframework.org/schema/beans      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">      <bean id="welcomeRedirect"         class="org.springframework.web.servlet.view.RedirectView">        <property name="url" value="welcomepage.htm" />     </bean>      </beans> 

The WelcomeController class in the com.gfg.controller handles the incoming URL request and maps it to the view page, here we use ModelAndView and redirect to the welcome page.

FIle: WelcomeController.java

Java
// Java Program to Illustrate WelcomeController Class  package com.gfg.controller;  // Importing required classes import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController;  // Class // Extending AbstractController interface public class WelcomeController extends AbstractController {      @Override     protected ModelAndView     handleRequestInternal(HttpServletRequest request,                           HttpServletResponse response)         throws Exception     {          return new ModelAndView("redirect:welcomepage.htm");     } } 

Step 3: After completing the application, your project structure would look something like this:

Now it's time to run your project in the Tomcat Server, after running the tomcat server type the URL http://localhost:8080/SpringMvcMultipleViewResolver/welcomepage.htm in your favorite browser.


Next Article
Spring MVC - Multiple Resolver Mapping

A

ashutosh44
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Java-Spring
  • Java-Spring-MVC
Practice Tags :
  • Java

Similar Reads

    Two-Way Data Binding in Spring MVC with Example
    Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a var
    7 min read
    Spring MVC - Basic Example using JSTL
    JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web
    8 min read
    Spring MVC @ModelAttribute Annotation with Example
    In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. For example, if we have a form with a form backing object that is called "Student" then we can ha
    8 min read
    Data Transfer Object (DTO) in Spring MVC with Example
    In Spring Framework, Data Transfer Object (DTO) is an object that carries data between processes. When you're working with a remote interface, each call is expensive. As a result, you need to reduce the number of calls. The solution is to create a Data Transfer Object that can hold all the data for
    7 min read
    Spring MVC - Capture and Display the Data from Registration Form
    This article is the continuation of this article Spring MVC - Create Registration Form using Form Tag Library, where we have successfully created a registration form using the Form Tag Library. Here in this article, we are going to explain how can we capture the data that are entered by the user and
    3 min read
    Spring MVC - Create Registration Form using Form Tag Library
    Spring Framework provides spring’s form tag library for JSP views in Spring’s Web MVC framework. In Spring Framework, we use Java Server Pages(JSP) as a view component to interact with the user. From version 2.0, Spring Framework provides a comprehensive set of data binding-aware tags. These tags ar
    7 min read
    Data Binding in Spring MVC with Example
    Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a var
    8 min read
    Spring MVC - Pagination with Example
    We will be explaining how we can implement pagination in Spring MVC Application. This is required when we need to show a lot of data on pages. Suppose in an e-commerce site we have a lot of products but we can't show all of those on a single page, so we will show only 20 products on each page. This
    3 min read
    Spring MVC Integration with MySQL
    Spring MVC is one of the most popular Java frameworks for building scalable web applications. When combined with MySQL, it provides a robust solution for developing data-driven applications. This article will guide you through integrating Spring MVC with MySQL, covering database setup, project confi
    7 min read
    OpenSource REST API URL and Retrieving Data From it By Using Spring MVC
    In this internet era, a lot of helper services are available in the form of REST API and mostly REST API provides us the details in the form of JSON/XML. We can use them in our applications and render the data as we like. Here is the list of a few opensource REST API URLs: API NameDescriptionURLCoin
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences