Spring MVC Tutorial
Spring MVC Tutorial
Spring MVC Tutorial
html
The DispatcherServlet
All HTTP requests and responses are handled by DispatcherServlet which is designed by Spring
MVC framework. Following diagram illustrates the request processing workflow of
DispatcherServlet.
Below are the events in sequence which corresponds to an HTTP request to DispatcherServlet.
1
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
HandlerMapping, Controller and ViewResolver components mentioned above are the parts of
WebApplicationContext. It is an extension to the plain ApplicationContext which has extra
features.
Required Configuration
Requests are mapped using a URL mapping in the web.xml file which DispatcherServlet wants
to handle. Below example shows the declaration and mapping for HelloWeb DispatcherServlet
example:
WebContent/WEB-INF directory of the web application will have web.xml file. Framework
will load the application context from file which has a name structure [servlet-name]-servlet.xml
which is under WebContent/WEB-INF directory upon initialization of HelloWeb
DispatcherServlet. In the example, file name will be HelloWeb-servlet.xml.
DispatcherServlet handles the URLs which are mentioned in <servlet-mapping> tag. In this
example, all the HTTP requests which are ending with .jsp are handled by HelloWeb
DispatcherServlet.
We can even customize the default file name and location which are [servlet-name]-servlet.xml
and WebContent/WEB-INF respectively by adding servlet listener i.e., ContextLoaderListener
in web.xml file as below-
<web-app...>
<!-------- DispatcherServlet definition goes here----->
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
2
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
Keeping the points together, let us see the required configuration for our example HelloWeb-
servlet.xml file that is placed in web application’s WebContent/WEB-INF directory:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-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.wisdomjobs" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
With the help of [servlet-name]-servlet.xml file we create the beans, by overriding the bean
definitions of any with same name in global scope.
Spring MVC annotation scanning capability is activated by <context:component-scan…> tag
which allows us to make use of @Controller and @RequestMapping etc annotations.
In the above example, a logical view name hello is assigned to a view implementation which is
located at /WEB-INF/jsp/hello.jsp. To resolve the view names, InternalResourceViewResolver
will define rules.
In coming section, we will show you how to create actual components in MVC framework i.e.,
Model, View and Controller.
Defining a Controller
DispatcherServlet assigns the incoming HTTP request to the controllers. The annotation
@Controller specifies a particular class which fulfill the role of a controller. To map a URL to
an entire class or a particular handler method, the annotation @RequestMapping is used.
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
3
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
We can rewrite the above controller to add additional attributes in @RequestMapping as below-
@Controller
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
From the above, the URL to which handler method is mapped is indicated by value attribute. The
method attribute on the other hand specifies the method, which handle the HTTP GET request.
Few important points regarding the controller defined in above example-
Service method will contain required business logic. Using this service method, we can even call
other methods if required.
Depending on the logic we define, a model is created within this method. Getter and setter are
created to the attributes which are accessed by the view for final output. Example above creates
a model with “message” as attribute.
The name of the view is returned from the service method as a String and the above example
returns us a “hello” view name.
There are many types of views for presentation technologies by Spring MVC which are HTML,
Excel worksheets, PDF, JSPs, XSLT, JSON, Velocity templates, Atom and RSS feeds etc. Most
commonly used are JSP which are written with JSTL. Let us create a hello view in /WEB-
INF/hello/hello.jsp:
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
In Controller, we have setup ${message} as the attribute. We can define many attributes inside
our view to display.
4
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
Latest version of SDK can be downloaded from Oracle’s Java site: Java SE Downloads.
Instructions to install JDK is provided in downloaded files. One can follow the instructions and
configure the setup. PATH and JAVA_HOME environment variables need to set for referring to
the directory which contains javac and java i.e., java_install_dir and java_install_dir/bin
respectively.
Set the below variables in the C:\autoexec.bat file if we are running Windows and the JDK is
installed in C:\jdk1.6.0_15.
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.6.0_15 while using C
shell, we must keep the following in our .chsrc file.
If any one of the Integrated Development Environment (IDE) like Borland JBuilder, IntelliJ
IDEA, Eclipse or Sun ONE Studio is used, need to compile and run a simple program to get a
confirmation that IDE knows where we installed Java or should setup properly as per the
document.
Check and download the latest version of Apache Commons Logging API from
http://commons.apache.org/logging/. Once the download is complete, unzip/unpack the binary
distribution into a suitable location for example in C:\commons-logging-1.1.1 on windows, or
/usr/local/commons-logging-1.1.1 on Linux/Unix. The location has the below jar files and other
documents etc.
5
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
CLASSPATH variable should be set in the directory or we will face problem when running our
application.
It’s preferred to use the latest version of Eclipse installed as the examples in this tutorial are
written using Eclipse IDE.
Download and install the latest Eclipse binaries from http://www.eclipse.org/downloads/. Once
the download is complete, unzip/unpack the binary distribution into a suitable location for
example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix. Set the PATH variable
appropriately.
We can start Eclipse simply by double clicking on eclipse.exe or by executing the following
commands.
%C:\eclipse\eclipse.exe
On Unix (Solaris, Linux, etc.), Eclipse can be started by executing the below commands.
$/usr/local/eclipse/eclipse
6
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
Once everything is set, we can move on to setting up Spring Framework. Below are the steps to
follow for downloading and installing the framework.
Need to decide on whether to install Spring on Windows or Unix and proceed to next
step. It is .zip file for Windows and .tz file for Unix.
Latest version of Spring Framework binaries can be downloaded from
http://repo.spring.io/release/org/springframework/spring.
I have downloaded spring-framework-4.3.1.RELEASE-dist.zip on my Windows machine
during this tutorial. After downloading, unzip the file which gives us the directory
structure in E:\spring as follows.
We will see all the libraries in E:\spring\libs. CLASSPATH variable should be set in this
directory or we will face problem when running our application. If Eclipse is used, then no need
to set CLASSPATH as Eclipse will set it.
7
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
We are ready to move to our first Spring example once we are done with the last step. We will
see the example in the next tutorial.
Step Description
1 Create a Dynamic Web Project with a name HelloWeb and create a package
com.wisdomJobsunder the src folder in the created project.
2 Drag and drop below mentioned Spring and other libraries into the folder
WebContent/WEB-INF/lib.
3 Create a Java class HelloController under the com.WisdomJobs package.
4 Create Spring configuration files web.xml and HelloWeb-servlet.xml under the
WebContent/WEB-INF folder.
5 Create a sub-folder with a name jsp under the WebContent/WEB-INF folder. Create a
view file hello.jsp under this sub-folder.
6 The final step is to create the content of all the source and configuration files and
export the application as explained below.
HelloController.java
package com.WisdomJobs;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
web.xml
8
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
HelloWeb-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-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.wisdomJobs" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
hello.jsp
Lastly, include the below list of Spring and libraries to include in our web application. We can
do this by drag and drop them in inWebContent/WEB-INF/lib folder.
servlet-api-x.y.z.jar
commons-logging-x.y.z.jar
spring-aop-x.y.z.jar
spring-beans-x.y.z.jar
spring-context-x.y.z.jar
spring-core-x.y.z.jar
spring-expression-x.y.z.jar
9
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
spring-webmvc-x.y.z.jar
spring-web-x.y.z.jar
Once the source and configuration files are created export the application. Do right click on the
application and Export > WAR File option and save HelloWeb.war file in Tomcat’s webapps
folder.
Start the Tomcat Server and using a standard browser check if you are having access to other
web pages from webapps folder. Try the URL http://localhost:8080/HelloWeb/hello and you
must see the below result if everything is fine with Spring Web Application:
From the above, we can see HelloWeb is the application name and hello is the virtual subfolder
in the URL. Those are mentioned in the controller like @RequestMapping("/hello"). Instead,
we can directly map the root by giving @RequestMapping("/"), if we give this the page can be
accessed by short URL http://localhost:8080/HelloWeb/ but it is recommended to have
different functionalities in different folders.
10
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
Step Description
4 The final step is to create the content of all the source and configuration files and export
the application as explained below.
Student.java
package com.wisdomjobs;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
11
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
StudentController.java
package com.wisdomjobs;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
In the above example, we are creating a service method called student(). We are passing a blank
Student object in ModelAndView object. In this object, command name is specified because the
framework expects an object with “command” name if we are using <form:form> tags in JSP
file. Student.jsp view is returned if student() method is called.
student.jsp
12
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp
Once the source and configuration files are created export the application. Do right click on the
application and Export> WAR File option and save HelloWeb.war file in Tomcat’s webapps
folder.
Start the Tomcat Server and using a standard browser check if you are having access to other
web pages from webapps folder. Try the URL http://localhost:8080/HelloWeb/index and you
must see the below result if everything is fine with Spring Web Application:
13
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
Submit the form once the required information is filled. You must see the below result if
everything is fine with Spring Web Application:
14
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
Step Description
2 Drag and drop below mentioned Spring and other libraries into the
folderWebContent/WEB-INF/lib.
6 The final step is to create the content of all the source and configuration
files and export the application as explained below.
WebController.java
packagecom.wisdomjobs;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:finalPage";
}
@RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage() {
return "final";
}
}
15
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<bean id = "viewResolver"
class =
"org.springframework.web.servlet.view.InternalResourceViewResolver">
</beans>
Below is the content of view file i.e., index.jsp. This page will send request to make use of
redirect service which redirects the request to other service method and finally a final.jsp page
will be displayed.
index.jsp
<%@tagliburi="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
16
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
Following is the content of Spring view file final.jsp. This is the final redirected page.
<%@tagliburi="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Redirected Page</h2>
</body>
</html>
Finally, following is the list of Spring and other libraries to be included in your web application.
You simply drag these files and drop them in WebContent/WEB-INF/lib folder.
commons-logging-x.y.z.jar
org.springframework.asm-x.y.z.jar
org.springframework.beans-x.y.z.jar
org.springframework.context-x.y.z.jar
org.springframework.core-x.y.z.jar
org.springframework.expression-x.y.z.jar
org.springframework.web.servlet-x.y.z.jar
org.springframework.web-x.y.z.jar
spring-web.jar
Once the source and configuration files are created export the application. Do right click on the
application and Export > WAR File option and save SpringWeb.war file in Tomcat’s webapps
folder.
Start the Tomcat Server and using a standard browser check if you are having access to other
web pages from webapps folder. Try the URL http://localhost:8080/SpringWeb/student and
you must see the below result if everything is fine with Spring Web Application:
17
Source: https://www.wisdomjobs.com/e-university/spring-mvc-framework-tutorial-1806.html
Submit the form by clicking “Redirect Page“ buttononce the required information is filled to get
redirected page. You must see the below result if everything is fine with Spring Web
Application:
18