Spring MVC Redirect Example
Spring MVC is one of the most important modules of the Spring framework. In this example, we will show how to write a simple Spring based web application which makes use of redirect to transfer an HTTP
request to another page.
1. Introduction
1.1 Spring Framework
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows developers to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring MVC Framework
Model-View-Controller (MVC) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:
- Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a
POJO
class which encapsulates the application data given by the controller - View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the
JSP
templates written with Java Standard Tag Library (JSTL
) - Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In spring framework, the controller part is played by the Dispatcher Servlet
1.2.1 Spring MVC Architecture and Flow
The main component of Spring MVC framework is the Dispatcher Servlet. Refer to the below diagram to understand the Spring MVC architecture.
In Spring 3 MVC framework Dispatcher Servlet access the front controller which handles all the incoming requests and queues them for forwarding to the different controllers.
- Dispatcher Servlet is configured in the
web.xml
of the application and all the requests mapped to this servlet will be handled by this servlet. Dispatcher Servlet delegates the request to the controller (i.e. class annotated with the@Controller
annotation) - The Controller class invokes the appropriate handler method based on the
@RequestMapping
annotation. This method returns the logical name of the View and the Model - Dispatcher Servlets resolves the actual view name using the
ViewResolver
(configured in the Spring Beans configuration file) and gets the actual view name - Passes the model object to the view so it can be used by view to display the result to the user
1.2.2 Advantages of Spring MVC Framework
- Supports RESTful URLs
- Annotation based configuration (i.e. developers may reduce the metadata file or less of configuration)
- Supports to plug with other MVC frameworks like
Struts
,Struts2
,JSF
etc - Flexible in supporting different View types like
JSP
,Velocity
,XML
,PDF
,Tiles
etc
Now, open up the Eclipse IDE and let’s see how to implement the redirection example in the Spring framework!
2. Spring MVC Redirect Example
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the ‘Maven Web App Archetype’ from the list of options and click Next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringMVCRedirect</groupId> <artifactId>SpringMVCRedirect</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
We can start adding the dependencies that developers want like Spring MVC etc. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependency for the Spring framework. The rest dependencies will be automatically resolved by Maven, such as Spring Core, Spring Beans, and Spring MVC etc. The updated file will have the following code:
pom.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>SpringMVCRedirect</groupId> <artifactId>SpringMVCRedirect</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringMVCRedirect Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- Servlet API Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- Spring Framework Dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.1.2.RELEASE</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}</finalName> </build> </project>
3.2 Java Class Creation
Let’s create the required Java files. Right-click on src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.spring.mvc.redirect.example
.
Once the package is created in the application, we will need to create the controller class. Right-click on the newly created package: New -> Class
.
A new pop window will open and enter the file name as WebRedirectController
. The controller class will be created inside the package: com.jcg.spring.mvc.redirect.example
.
3.2.1 Implementation of Controller Class
It is a simple class where the @Controller
annotation is used to specify this class as a Spring controller and the @RequestMapping
annotation specifies that the welcome()
method will handle a GET
request with the URL /
(i.e. the default page of the application). Add the following code to it:
WebRedirectController.java
package com.jcg.spring.mvc.redirect.example; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebRedirectController { @RequestMapping(value = "/welcome", method = RequestMethod.GET) public String welcome() { System.out.println("Application Startup Welcome Page"); return "welcome"; } @RequestMapping(value = "/redirect_page", method = RequestMethod.GET) public String redirect() { System.out.println("Redirecting Result To The Final Page"); return "redirect:final_page"; } @RequestMapping(value = "/final_page", method = RequestMethod.GET) public String finalPage() { System.out.println("Showing The Redirected Page"); return "final"; } }
3.3 Configuration Files
Let’s write all the configuration files involved in this application.
3.3.1 Spring Configuration File
To configure the Spring framework, we need to implement a bean configuration file i.e. spring-servlet.xml
which provides an interface between the basic Java class and the outside world. Right-click on SpringMVCRedirect/src/main/webapp/WEB-INF
folder, New -> Other
.
A new pop window will open and select the wizard as an XML
file.
Again, a pop-up window will open. Verify the parent folder location as: SpringMVCRedirect/src/main/webapp/WEB-INF
and enter the file name as: spring-servlet.xml
. Click Finish.
Once the XML
file is created, we will add the following code to it:
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.jcg.spring.mvc.redirect.example" /> <!-- Resolves Views Selected For Rendering by @Controllers to *.jsp Resources in the /WEB-INF/ Folder --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
Notes:
This file is loaded by the Spring’s Dispatcher Servlet which receives all requests coming into the application and dispatches processing for the controllers, based on the configuration specified in this spring-servlet.xml
file. Let’s look at some default configurations:
InternalResourceViewResolver
: This bean declaration tells the framework how to find the physicalJSP
files according to the logical view names returned by the controllers, by attaching the prefix and the suffix to a view name. For e.g. If a controller’s method returnshome
as the logical view name, then the framework will find a physical filehome.jsp
under the/WEB-INF/views
directorycontext:component-scan
: This tells the framework which packages to be scanned when using the annotation-based strategy. Here the framework will scan all classes under the package:com.jcg.spring.mvc.example
3.3.2 Web Deployment Descriptor
The web.xml
file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- Spring Configuration - Processes Application Requests --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.4 Creating JSP View
Spring MVC supports many types of views for different presentation technologies. These include – JSP
, HTML
, XML
etc. So let us write a simple view in SpringMVC/src/main/webapp/WEB-INF/views
. Right-click on SpringMVCRedirect/src/main/webapp/WEB-INF/views
folder, New -> JSP File
.
Verify the parent folder location as: SpringMVCRedirect/src/main/webapp/WEB-INF/views
and enter the filename as: welcome.jsp
. Click Finish.
This will be a landing page, where it will send a request to access the redirect()
method which in turn will redirect this request to another service method (i.e. finalPage()
) and finally a final.jsp
page will be displayed. Add the following code to it:
welcome.jsp
<!DOCTYPE HTML> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Sping MVC Redirection Application</title> </head> <body> <h2>Spring Page Redirection Example</h2> <div id="welcomeTextDiv"> <span id="btnText" style="padding-left: 24px;">!! Click Below Button To Redirect The Result To The New Page !!</span> <div id="redirectBtnTable" style="padding: 23px 0px 0px 35px;"> <form:form id="redirectionForm" action="redirect_page" method="GET"> <table> <tbody> <tr> <td> <input id="redirectBtn" type="submit" value="Redirect Page" /> </td> </tr> </tbody> </table> </form:form> </div> </div> </body> </html>
Repeat the step (i.e. Fig. 15) and enter the filename as: final.jsp
.
This will be the final redirected page and add the following code it:
final.jsp
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Sping MVC Redirection Application</title> </head> <body> <h2>Spring Page Redirection Example</h2> <div id="welcomeMessage" style="margin: 20px; color: green;"> <strong>Welcome! This Is A Redirected Page</strong> </div> </body> </html>
4. Run the Application
As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.
5. Project Demo
Open your favorite browser and hit the following URL. The output page will be displayed.
http://localhost:8085/SpringMVCRedirect/welcome
Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!
Now click on Redirect Page
button to submit the form and to get the final redirected page. Developers should see the following result if everything is fine with their application.
That’s all for this post. Happy Learning!!
6. Conclusion
In this section, developers learned how to download, create a new project in Eclipse IDE, and add Spring 3.0 library files to write a simple Spring MVC Redirect tutorial. That’s all for the Spring MVC tutorial and I hope this article served you whatever you were looking for.
7. Download the Eclipse Project
This was an example of Spring MVC Redirect for beginners.
You can download the full source code of this example here: Spring MVC Redirect