Search Tutorials


Spring MVC Tutorials | JavaInUse

Creating our first MVC program



Overview

Before we start writing our first Spring MVC program, lets understand how this is implemented in Spring.

Previously when using JSP Servlets, one had to configure a Servlet for each incoming request. In Spring MVC this is not the case, we do not have to configure any servlet. Spring MVC makes use of a pre-configured servlet called DispatcherServlet. We only make use of this DispatcherServlet to route the incoming request to the correct Controller and View and return it to the user.

Lets take an example. Here we will be designing an Employee Management System. Here the user requests to display all Employees information.
final-mvc2-uml
Here the User requests to show all the Employees information in the system. The client browser sends the displayAllEmployees.do request. This request is received by the DispatcherServlet. The DispatcherServlet then routes this request to the correct Controller, in this case the DisplayEmployeeController.java. The DisplayEmployeeController.java does the actual process of retrieving the Employee info. After this it returns to the DispatcherServlet the Model Data which represents all the Employee info retrieved and the view details which will show this model data. The View name returned in our case is displayEmployees.jsp. The ServletDispatcher then routes this data to the ViewResolver. The ViewResolver then selects the correct View, populates it with the Model Data and returns it to DispatcherServlet. The DispatcherServlet then returns this populated View to the client.

Lets Begin

In the previous chapter we configured the Development Environment required for writing Spring MVC.
We will create Eclipse Maven project as follows-
final-mvc2-1

We will have to add one more additional dependency to the pom.xml configured in the previous chapter. We add the jstl dependency required for displaying elements in the jsp page. So our pom will be-
<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.test</groupId>
	<artifactId>employee-management-system</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>employee-management-system 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>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>employee-management-system</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
			</plugin>
		</plugins>
	</build>
</project>
Next we configure DispatcherServlet in web.xml.Here all the incoming request with .do extension will now be routed by the DispatcherServlet to the configured Controllers.-
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
	version="2.5">

	<!-- Configure the Disptcher Servlet -->
	<servlet>
		<servlet-name>Dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Filter the incoming requests for the .do pattern -->
	<servlet-mapping>
		<servlet-name>Dispatcher</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>


Next we will write Application Context to configure the beans. Spring MVC automatically loads a application context with the name- <servlet-name>-servlet.xml. So in our case Spring will automatically load the Application Context named as Dispatcher-servlet.xml.
In this configuration file we have written code to scan the packages com.javainuse.controller and "com.javainuse.service.
<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:mvc="http://www.springframework.org/schema/mvc" 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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


	<!-- Scan these packages for Annotated classes -->
	<context:component-scan base-package="com.javainuse.controller" />
	<context:component-scan base-package="com.javainuse.service" />
	<mvc:annotation-driven />
</beans>
Now lets write our Java classes. First we write the Domain class Employee.java-
 
package com.javainuse.domain;

public class Employee {

	private String empId;
	private String name;
	private String designation;
	private double salary;

	public Employee() {
	}

	public Employee(String empId, String name, String designation, double salary) {
		super();
		this.setEmpId(empId);
		this.name = name;
		this.designation = designation;
		this.salary = salary;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	public String getEmpId() {
		return empId;
	}

	public void setEmpId(String empId) {
		this.empId = empId;
	}

}
Next we write the controller. Above in the Dispatcher-context.xml we have context:component-scan base-package="com.javainuse.controller". So Spring scans this particular package for a class annotated with @Controller. The DisplayEmployeeController has a dependency of EmployeeService.java. In DisplayEmployeeController we have a method viewAllItems which has been mapped to the URL /viewAllEmployees. In the xml configuration files we have configured the DispatcherServlet such that when the client hits viewAllItems.do the DispatcherServlet scans the package com.javainuse.controller looking for Controller. The DisplayEmployeeController returns ModelAndView containing the populated Model class Employee and the View name. Currently in our configurations we have not specified any ViewResolver. So by default Spring will use the default InternalResourceViewResolver. In the next chapters we will look at the other view resolvers.

We will write a class DisplayEmployeeController as follows-
  
package com.javainuse.controller;

import java.util.List;

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

import com.javainuse.domain.Employee;
import com.javainuse.service.EmployeeService;

@Controller
public class DisplayEmployeeController {

	@Autowired
	private EmployeeService employeeService;

	@RequestMapping("/viewAllEmployees")
	public ModelAndView viewAllItems() {
		List<Employee> allEmployees = employeeService.getAllEmployees();
		return new ModelAndView("/displayAllEmployees.jsp", "allEmployees",
				allEmployees);
	}
}
In DisplayEmployeeController we have autowired EmployeeService class. Also in the Dispatcher-context.xml we have context:component-scan base-package="com.javainuse.service" Spring scans this particular package for a class annotated with @Component. The EmployeeService class will actually fetch all the required Employee information. Usually EmployeeService should call the EmployeeDAO which will return all items from the DataBase.But here we will mock the EmployeeService class to just return the list of items as follows. We are using the Programming to Interface concept here. You can read more about this in this chapter. So we create the EmployeeService.java and EmployeeServiceMockImpl.java as follows.
  
package com.javainuse.service;

import java.util.List;

import com.javainuse.domain.Employee;

public interface EmployeeService {
	public List<Employee> getAllEmployees();

}
  
package com.javainuse.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.javainuse.domain.Employee;

@Component
public class EmployeeServiceMockImpl implements EmployeeService {

	private List<Employee> testEmployees = new ArrayList<Employee>();

	// populate the Employee List
	public EmployeeServiceMockImpl() {
		testEmployees.add(new Employee("1", "emp1", "M1", 10000));
		testEmployees.add(new Employee("2", "emp2", "M2", 20000));
		testEmployees.add(new Employee("3", "emp3", "M3", 30000));
		testEmployees.add(new Employee("4", "emp4", "M4", 40000));
		testEmployees.add(new Employee("5", "emp5", "M5", 50000));
		testEmployees.add(new Employee("6", "emp6", "M6", 60000));
	}

	// Return the Mocked Employee List
	public List<Employee> getAllEmployees() {
		return new ArrayList<Employee>(testEmployees);
	}
}
The DisplayEmployeeController returns the list of employees to a JSP page called displayAllEmployees.jsp using the following code statement
return new ModelAndView("/displayAllEmployees.jsp", "allEmployees", allEmployees);
We will write the displayAllEmployees JSP page to display the Employee List allEmployees as follows-
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show Employees</title>
</head>
<body>
	<div id="books">
		<ul>
			<c:forEach items="" var="nextEmp">
				<li>
					<h2></h2>
					<h2></h2>
					<h2></h2>
					<h2></h2>
				</li>
			</c:forEach>
		</ul>
	</div>
</body>
</html>
We now run the two eclipse commands- clean install, tomcat:run to deploy the application. Now open a browser and hit the URL http://localhost:8080/employee-management-system/viewAllEmployees.do. We will see the Employee info as follows-
final-mvc2-2

Download Source Code

Download it - Spring-MVC Project

What Next?

In the next chapter will implement Spring MVC: Add Employee Functionality without Spring Form Handling.