Spring MVC tutorial with example

Spring MVC

In web development MVC architecture is widely used to build a robust web application. Spring MVC provides you components to build your web application in MVC architecture. Main advantage of Spring is that it can easily be integrated with other technologies like Struts, JSF, Velocity, etc. Spring MVC gives you highly configurable structure. 

Lifecycle of Spring MVC:

1. The HTTP request by the user will be intercepted by the DispatcherServlet. DispatcherServlet is called as Front Controller.
2. Front controller will find out the appropriate controller with the help of handler mapping
3. Front controller then delegates the request to the controller
4. Controller will process the request and create the ModelView object. The ModelView will be returned to the front controller
5. Front controller then will use view resolver to find out appropriate view name.
6. The selected view will be rendered now.

Sample Application:

This sample application is annotation driven. I have used annotations instead of spring xml configuration. 

This application is having two views namely view1, view2 both are jsp pages. Based on the URL mapping the controller will render appropriate view to the user.
My sample application name is SpringMVC.


Before starting the application make sure that you are having a server ( I have used Tomcat 7) and below libraries;

jstl-1.2.jar (Only if you use jstl in your application)

Project Structure:

Configuring web.xml

First you need to configure front controller/DispatcherServlet in the web.xml file of your web application.
and ViewResolver configuration as follows.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">

Configure contextClass parameter to org.springframework.web.context.support.AnnotationConfigWebApplicationContext and contextConfigLocation parameter to the package in which you are creating the controllers. These configurations are used in annotation driven application.

Creating Configuration Class:

Annotation driven configuration file is used to create view resolver. 
@Configuration annotation says that this class is a configuration class
@ComponentScan annotation is used to specify the controllers package name. 

package com.compiletimeerror.beans;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

 * @author Vienna
@ComponentScan(basePackages = "com.compiletimeerror.controller")
public class MyConfig {
 public InternalResourceViewResolver getResourceViewResolver() {
  InternalResourceViewResolver resourceViewResolver = new InternalResourceViewResolver();
  return resourceViewResolver;

InternalResourceViewResolver is the subclass of UrlBasedViewResolver which is used to internal views which can be a html file or jsp file based on the url pattern given. We can configure the prefix and suffix values to identify a view.
The view name is identified as PREFIX+VIEW NAME+SUFFIX.
In this example /WEB-INF/views/viewname.jsp

It is advisable to keep all the views inside web-inf folder of the application. This prevents the direct access of the views from the browser. Only the controllers can access the views.
Note that this configuration can also be given in xml file. I have not given it here to avoid confusions.

Creating the Controller:

Create a controller class inside the package mentioned in above configuration file's @ComponentScan annotation.

package com.compiletimeerror.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

 * @author Vienna
public class MyController {
 public String loadView1(Model m){
  m.addAttribute("name","Hello world view 1");
  return "view1";
 public String loadView2(Model m){
  m.addAttribute("name","Hello world view 2");
  return "view2";

@Controller annotation is used to define that this class is a controller class.
@RequestMapping annotations is used to define which method is to be used for a particular URL pattern.
In this example the URL pattern 'view1' is configured to loadView1() method and the URL pattern 'view2' is configured to loadView2() method.

Inside the methods we have to create the ModelView objects and return.
addAttribute() method of the Model is used to create model properties. In this example I have created a property called 'name' and assigned 'Hello world view1' string as the value of the property. This can be fetched in the jsp page using the jstl ${name}.
return "view1" is the name of the view to be rendered.
In simple, a model with a property 'name' with value 'Hello world view1' will be passed to the view with name 'view1'.

You can also create the model view using below syntax;
return new ModelAndView("view1", "name", "Hello world view1");
'view1' is the name of the view
'name' is the model property
'Hello world view1' is the value of the property.

Creating Views:

Now its time to create the views inside /WEB-INF/views/ folder.
I have created two jsp files namely view1.jsp, view2.jsp. Both the jsp files are displaying the value of the model property name using the jstl  ${name}


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Running the Application:

We are done with the application. Deploy the application in Tomcat 7 server. To deploy, right click on the project>Run as>Run on server>Select Tomcat 7 and click Finish.

In the browser address bar give the url of the view1 as follows and press enter;
Now the view1.jsp will be rendered and the value passed in the Model will be displayed in the page.

Similarly run the view2 url;
This will load view2.jsp and display the Model value.

Sourcecode of this application: with dependencies



Post a Comment