Spring MVC Tutorials

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Spring MVC is part of Spring Framework as a MVC implementation. Spring MVC is very much light weight and flexible web framework that are getting popular in these days. It provides a rich functionality for building robust Web Applications. Spring can integrate effortlessly with other popular Web Frameworks like Struts, Java Server Faces and Tapestry. It means that you can even instruct Spring to use any one of the Web Frameworks. More than that Spring is not tightly coupled with Servlets or JSP to render the View to the Clients. Integration with other View technologies like Velocity, Freemarker, Excel or Pdf is also possible now.

Spring MVC include input logic, business logic and UI logic.

  • The Model contains the application information and consists of POJO. It notifies you about the change in state to its associated views and controllers.
  • The view renders the information sent by the model. Basically, it generates HTML files as output that is interpreted by client browsers.
  • The controller acts as a mediator between the view and model. It updates the model`s state and tells the view to render the model`s information. The spring web Model View Controller (MVC) framework is created around DispatcherServlet that handles a sequence of events, which occur corresponding to incoming HTTP requests and responses.

Spring MVC flow is as follows:

Spring MVC flow

  • After receiving an HTTP request, DispatcherServlet consults HandlerMapping to call the appropriate controller.
  • The controller then takes the request and calls the respective service methods. The service methods return the appropriate view name to the DispatcherServlet on the basis of defined business logic.
  • The DispatcherServlet will then ask ViewResolver to give it a defined view based on the request
  • Once the view is selected, DispatcherServlet passes the model information to the view, which is rendered in the browser.

Spring MVC Hello World Example

Create maven project in eclipse or STS. Here is the project directory structure.

Spring Hello World

Now you add maven dependency in the POM file.

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>springmvchelloexample</groupId>
  <artifactId>springmvchelloexample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>javax.servlet</groupId>
  		<artifactId>servlet-api</artifactId>
  		<version>3.0-alpha-1</version>
  	</dependency>
  	<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>
</project>
Create index.jsp whenever you run the project this page will open and after click on the click here link it will call the controller class.

Index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<a href="hello.html">click here</a>
</body>
</html>
Create the controller class HelloController:

In this class you have seen two annotations @Controller and @RequestMapping.

@Controller is used here to specify this class is a Spring controller and the @RequestMapping annotation specifies that the helloWorldPrint() method will handle a GET request with the url and finally controller class returns the instance of ModelAndView controller with the message name and value, message value will be display in the helloview.jsp page.

HelloController.java


package com.javatutsworld;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
	@RequestMapping("/hello")
	public ModelAndView helloWorldPrint() {
		String message = "HELLO This is Spring mvc hello world example";
		return new ModelAndView("helloview", "message", message);
	}
}
Create web.xml

You specify the servlet class DispatcherServlet which acts as the front controller in Spring Web MVC

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">
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
</web-app>  
Create the spring-servlet.xml

This configuration file is used to specify the ViewResolver and View components.

context:component-scan element is used to provide the base-package location for scanning Controller classes. You have to give the value of top-level package at the time of project creation.

InternalResourceViewResolver is the view resolver; you can provide view pages location through prefix and suffix properties. So all your JSP pages should be in /WEB-INF/jsp/ directory.

This spring-servlet.xml file should be located inside the WEB-INF directory.

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.javatutsworld" />
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>  
Create the helloview.jsp

This JSP page will display the message which is returned by the Controller.

helloview.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Output: ${message}
</body>
</html>

Output

Spring Hello World

      Advertisements