Spring MVC Hello World Example

In this example, we will build a hello world web application using the Spring MVC framework. Spring MVC is one of the most important modules of the Spring framework. It builds on the powerful Spring IoC container and makes extensive use of the container features to simplify its configuration.

Table Of Contents

What is MVC Framework?
Dispatcher Servlet (Spring Controller)
Spring MVC Hello World Example
	Runtime Dependencies
	Configuration Files web.xml and spring-servlet.xml
	Request Handler EmployeeController.java
	View Model EmployeeVO.java
	Dao Classes
	Service layer Classes
	View employeesListDisplay.jsp

What is MVC Framework?

Model-view-controller (MVC) is a well known design pattern for designing UI based applications. It mainly decouples business logic from UIs by separating the roles of model, view, and controller in an application. Usually, models are responsible for encapsulating application data for views to present. Views should only present this data, without including any business logic. And controllers are responsible for receiving requests from users and invoking back-end services (manager or dao) for business logic processing. After processing, back-end services may return some data for views to present. Controllers collect this data and prepare models for views to present. The core idea of the MVC pattern is to separate business logic from UIs to allow them to change independently without affecting each other.


In a Spring MVC application, models usually consist of POJO objects that are processed by the service layer and persisted by the persistence layer. Views are usually JSP templates written with Java Standard Tag Library (JSTL). Controller part is played by dispatcher servlet which we will learn about in this tutorial in more detail.

Some developers consider the service layer and DAO layers classes as part of model component in MVC. I have a different opinion on this. I do not consider service and DAO layers classes the part of MVC framework. Usually a web application is 3-tier architecture i.e. data-service-presentation. MVC is actually part of presentation layer.

3 tier architecture with mvc part of it

Dispatcher Servlet (Spring Controller)

In the simplest Spring MVC application, a controller is the only servlet you need to configure in a Java web deployment descriptor (i.e., the web.xml file). A Spring MVC controller—often referred to as a Dispatcher Servlet implements front controller design pattern and every web request must go through it so that it can manage the entire request life cycle.

When a web request is sent to a Spring MVC application, dispatcher servlet first receives the request. Then it organizes the different components configured in Spring’s web application context (e.g. actual request handler controller and view resolvers) or annotations present in the controller itself, all needed to handle the request.

Spring dispatcher servlet
Spring dispatcher servlet

To define a controller class in Spring 3.0, a class has to be marked with the @Controller annotation. When a @Controller annotated controller receives a request, it looks for an appropriate handler method to handle the request. This requires that a controller class map each request to a handler method by one or more handler mappings. In order to do so, a controller class’s methods are decorated with the @RequestMapping annotation, making them handler methods.

After a handler method has finished processing the request, it delegates control to a view, which is represented as handler method’s return value. To provide a flexible approach, a handler method’s return value doesn’t represent a view’s implementation but rather a logical view i.e. without any file extension. You can map these logical views to right implementation into applicationContext file so that you can easily change your view layer code without even touching request handler class code.

To resolve the correct file for a logical name is the responsibility of view resolvers. Once the controller class has resolved a view name into a view implementation, per the view implementation’s design, it renders the objects.

Spring MVC Hello World Example

In this application, I am creating most simple employee management application demo having only one feature i.e. list all available employees in system. Let’s note down the directory structure of this application.

Spring mvc hello world directory structure
Spring mvc hello world directory structure

Now let’s write all the files involved into this hello world application.


Below pom.xml file contains dependencies for spring mvc and taglibs support for writing jsp files.

<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">
	<name>springmvcexample Maven Webapp</name>
		<!-- Spring MVC support -->

		<!-- Tag libs support for view layer -->



This minimum web.xml file declares one servlet (i.e. dispatcher servlet) to receive all kind of requests. Dispatcher servlet here acts as front controller.

<web-app id="WebApp_ID" version="2.4" 
	<display-name>Spring Web MVC Hello World Application</display-name>



spring-servlet.xml (You can have applicationContext.xml as well)

We are using annotated classes at request handler, service and dao layer so I have enabled annotation processing for all class files in base package “com.howtodoinjava.demo“.

<beans xmlns="http://www.springframework.org/schema/beans"

	<context:component-scan base-package="com.howtodoinjava.demo" />

	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	    <property name="prefix" value="/WEB-INF/views/" />
	    <property name="suffix" value=".jsp" />



Annotation @RequestMapping at class level and method level determine the URL at which method will be invoked.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.howtodoinjava.demo.service.EmployeeManager;

public class EmployeeController 
	EmployeeManager manager;

	@RequestMapping(value = "/getAllEmployees", method = RequestMethod.GET)
	public String getAllEmployees(Model model)
		model.addAttribute("employees", manager.getAllEmployees());
		return "employeesListDisplay";

Read More : How to use @Component, @Repository, @Service and @Controller Annotations?


This class act as model for MVC pattern.

package com.howtodoinjava.demo.model;

import java.io.Serializable;

public class EmployeeVO implements Serializable 
	private static final long serialVersionUID = 1L;

	private Integer id;
	private String firstName;
	private String lastName;

	//Setters and Getters

	public String toString() {
		return "EmployeeVO [id=" + id + ", firstName=" + firstName
				+ ", lastName=" + lastName + "]";


The classes at third tier in 3-tier architecture. Responsible for interacting with underlying DB storage.

import java.util.List;

import com.howtodoinjava.demo.model.EmployeeVO;

public interface EmployeeDAO 
	public List<EmployeeVO> getAllEmployees();


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

import org.springframework.stereotype.Repository;

import com.howtodoinjava.demo.model.EmployeeVO;

public class EmployeeDAOImpl implements EmployeeDAO {

	public List<EmployeeVO> getAllEmployees() 
		List<EmployeeVO> employees = new ArrayList<EmployeeVO>();
		EmployeeVO vo1 = new EmployeeVO();
		EmployeeVO vo2 = new EmployeeVO();
		return employees;


The classes at second tier in 3-tier architecture. Responsible for interacting with DAO Layer.

import java.util.List;

import com.howtodoinjava.demo.model.EmployeeVO;

public interface EmployeeManager 
	public List<EmployeeVO> getAllEmployees();


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.howtodoinjava.demo.dao.EmployeeDAO;
import com.howtodoinjava.demo.model.EmployeeVO;

public class EmployeeManagerImpl implements EmployeeManager {

	EmployeeDAO dao;
	public List<EmployeeVO> getAllEmployees() 
		return dao.getAllEmployees();


This jsp is used to display all the employees in system. It iterates the collection of employees in loop, and print their details in a table. This fits into view layer of MVC pattern.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

	<title>Spring MVC Hello World</title>

	<h2>All Employees in System</h2>

	<table border="1">
			<th>Employee Id</th>
			<th>First Name</th>
			<th>Last Name</th>
		<c:forEach items="${employees}" var="employee">


Now deploy the application in your application server (i am using tomcat 7). And hit the URL “http://localhost:8080/springmvcexample/employee-module/getAllEmployees“. You will see below screen if you have configured everything correctly.

Application front UI
Application front UI

Drop me comments if something not working for you or is not clear in this tutorial.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

20 thoughts on “Spring MVC Hello World Example”

  1. How does Spring know where to find your Bean config file (spring-servlet.xml)? Other examples that I’ve seen specifies that location of that file with with in web.xml, or by AnnotationConfigWebApplicationContext class using pure Java configuration.

    • Ideally you should use contextConfigLocation as below.




      If you do not specify, then spring will automatically look for +”-“+servlet.xml in the WEB-INF folder.

  2. I really struggled very hard to get this :

    It would be more useful if you specify the development environment.

    I had to change the spring-servlet.xml as below to get the output.

  3. I tried the above example in my own way. in that I did not know how to configure the xml file for above program it shows the error repeatedly(File not found like).
    Will you please explain how to configure and what are the files need to be configured

    • there is no data displayed in the .jsp because the list was not set to page/request/session/application attribute.
      you need to set it in the controller
      ex: request.setAttribute(“employees”, employees); or session.setAttribute(“employees”, employees);

  4. hey i am start to use spring mvc 5.0.9 and use java based configuration , when try to access my jsp page
    i get the folowing error message
    Type Status Report

    Message /Contactapp/WEB-INF/view/ hello.jsp

    Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
    Apache Tomcat/9.0.8

  5. the first one is to show different parts’ name,like employee or tourist
    then url will be “http://localhost:8080/projectName/tourist/
    the second one is to show one part’s method name. like login or logout
    then url will be “http://localhost:8080/projectName/employee/login
    hope to fix your problem.

  6. Hi Lokesh,
    your articles are simple to read and understand.
    I have a question – what is the need of EmployeeManager and EmployeeManagerImpl classes here
    Why you call ‘manager.getAllEmployees()’, instead we can call directly ‘dao.getAllEmployees()’ by using EmployeeDAO class.
    Please clarify us.

  7. How view page(jsp) gets to know about model attribute “employees” and gets iterated.?
    Are we can manually configure all the request maping to handlermapping ??? Can you please elaborate this

    • @ModelAttribute binds a method parameter or method return value to a named model attribute, exposed to a web view. It is essentially form backing object. After controller method execution, it’s data is copied to to both HttpServletRequest and HttpSession and thus accessible to JSP.

    • The class level maps to a url, and the second within the class maps to an even further extension. So class level starts it, and you can keep digging further into different pages.

      So class level takes you too localhost:8080/employee-module

      The method within the class takes you to localhost8080/employee-module/getAllEmployees

  8. Hi – In the above example, can you pls add exception handling using @ExceptionHandler or @ControllerAdvice and illustrate how to handle exceptions thrown from DAO layer, via a common exception handling class in the controller layer?


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.