Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Spring MVC Example

Sometime back in Spring MVC Tutorial, I explained how to create Spring MVC application using Spring Tool Suite. But today, I will be creating a basic hello world spring MVC application using maven and Eclipse.

Spring MVC Example

Spring MVC is based on Model-View-Controller architecture.

DispatcherServlet is the front controller class to take all requests and start processing them. We have to configure it in web.xml file. Its job is to pass request to appropriate controller class and send the response back when view pages have rendered the response page. will be the single controller class in our spring mvc example application. home.jsp, user.jsp are the view pages in our spring mvc hello world example application. will be the only model class we will have in our spring mvc example web application.

Spring MVC Example Hello World Eclipse Project

Below image shows our Spring MVC example project in Eclipse.

Let’s Get Started and Create Our Project Right from the Scratch

Spring MVC Example Eclipse Project Setup

Since it’s a web application and we want to use maven for dependencies management, first of all we have to create a dynamic web application and then convert it to a maven project. Below images show how to do this and get our project skeleton structure ready. Right click on the project explorer window and click on “New -> Dynamic Web Project” as shown in below image.

Provide name as “spring-mvc-example” in the next popup page, rest of the things should not required to be changed.

On next page, provide the source folder as “src/main/java”. You might have to remove “src” folder from the list before adding this.

Next is the web module page, provide the context root of application as “spring-mvc-example” and make sure to check “Generate web.xml deployment descriptor” option.

Click on Finish and you will have a new Dynamic Web Project in your Eclipse project explorer.

Converting Dynamic Web Project to Maven Project

We want to use Maven to easily manage our Spring MVC dependencies. So let’s convert our web project to Maven. Right click on the project and select “Configure -> Convert to Maven Project”.

Next provide the pom.xml configurations as shown below.

Our maven web application project skeleton code is ready. Now we can start making changes to it and create our Spring MVC hello world example application.

Spring MVC Dependencies to pom.xml

We need to add spring-web and spring-webmvc dependencies in pom.xml, also add servlet-api, jsp-api and jstl dependencies. Our final pom.xml file will be like below.

<project xmlns="" xmlns:xsi=""
    <name>Spring MVC Example</name>
    <description>Spring MVC Hello World Example</description>

    <!-- Add Spring Web and MVC dependencies -->
        <!-- Servlet -->

        <finalName>${project.artifactId}</finalName> <!-- added to remove Version from WAR file -->

Notice the finalName configuration in build, so that our WAR file name doesn’t have version details. When the project is built by Eclipse, you will notice all the jars showing up in maven dependencies section.

Spring MVC DispatcherServlet as Front Controller

We have to add Spring MVC framework to our web application, for that we need to configure DispatcherServlet in web.xml as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">

  <!-- Add Spring MVC DispatcherServlet as front controller -->

contextConfigLocation init-param is used to provide the location of spring bean configuration file.

Spring MVC Example Bean Configuration File

Next step is to create spring bean configuration file spring-servlet.xml as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns=""
  xmlns:xsi="" xmlns:beans=""

  <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

  <!-- Enables the Spring MVC @Controller programming model -->
  <annotation-driven />
  <context:component-scan base-package="com.journaldev.spring" />

  <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
  <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />


There are three important configurations.

  1. annotation-driven tells DispatcherServlet to look for Controller classes using @Controller annotation.
  2. context:component-scan tells DispatcherServlet where to look for controller classes.
  3. InternalResourceViewResolver bean configuration to specify location of view pages and suffix used. Controller class methods return name of the view page and then suffix is added to figure out the view page to use for rendering the response.

Spring MVC Controller Class

We have a single controller class to respond for two URIs – “/” for home page and “/user” for user page.

package com.journaldev.spring.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

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

import com.journaldev.spring.model.User;

public class HomeController {

     * Simply selects the home view to render by returning its name.
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        System.out.println("Home Page Requested, locale = " + locale);
        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate);

        return "home";

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public String user(@Validated User user, Model model) {
        System.out.println("User Page Requested");
        model.addAttribute("userName", user.getUserName());
        return "user";

Note that for simplicity, I have not used any logging framework such as log4j.

Spring MVC Model Class

We have a simple model class with a single variable and its getter-setter methods. It’s a simple POJO class.

package com.journaldev.spring.model;

public class User {
    private String userName;

    public String getUserName() {
        return userName;

    public void setUserName(String userName) {
        this.userName = userName;

Spring MVC View Pages

We have two view pages as defined below. home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
<%@ taglib uri="" prefix="c"%>
<%@ page session="false"%>
    <h1>Hello world!</h1>

    <P>The time on the server is ${serverTime}.</p>

    <form action="user" method="post">
        <input type="text" name="userName"><br> <input
            type="submit" value="Login">


<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Home Page</title>
<h3>Hi ${userName}</h3>

Notice that Spring MVC takes care of mapping form variables to model class variables, that’s why we have the same variable name in both places. That’s it, our Spring MVC example project is ready to be deployed and tested.

Spring MVC Eclipse Project Deployment

We can use Eclipse export as WAR file option to deploy it directly to any running Tomcat server webapps directory. However, you can also use the command line to build the project and then copy it into your favorite servlet container deployment directory.

Spring MVC Example Test

Once the spring mvc project is deployed, we can access the home page at https://localhost:8080/spring-mvc-example/. Change the Tomcat port and context-root accordingly.

That’s all for Spring MVC example, I have tried to keep it as simple as possible.

Start Your Free Trial and Elevate Your Cloud Experience Today!

Ready to transform your cloud journey? Join our hands-on trial and discover the power and flexibility of our cloud solutions. With instant access to cutting-edge features and a user-friendly interface.

Try for free!