Spring 4 MVC HelloWorld Tutorial – Full XML Example

This tutorial introduces you to Spring MVC 4 basics, using classic Hello World example without skipping any step. Spring 4 MVC HelloWorld Tutorial – Annotation/JavaConfig Example contains the Annotations based full example. Let’s get going.

Following technologies being used:

  • Spring 4.0.6.RELEASE
  • Maven 3
  • JDK 1.6
  • Eclipse JUNO Service Release 2
  • M2Eclipse plugin (Optional)

Feel free to skip Step 1, if you are already familiar with creating a maven project with eclipse.

Let’s begin.

Step 1 : Create a new Maven webapp project in Eclipse

Goto File-> New -> Maven Project,


Uncheck “Use default Workspace location” in case you prefer to create the project on another location

click Next


Select maven web app archetype from the list of Options, click Next


Provide Group Id, Artifact Id, version as shown above, and click Finish.Refresh your project

You should get the file structure as shown below


Note: In case you do not see the src/main/java and src/test/java folder in your project structure, goto Project>Properties>Java BuildPath>Libraries, select/change-to appropriate Java version, click ok, you should see those folders now.

Note: With recent Eclipse versions you don’t need to use mvn eclise:eclipse anymore, this functionality is built-in with m2e eclipse plugin.

Step 2: Provide Spring dependencies in Maven pom.xml

Since it’s a maven project, all the project dependencies can be configured in pom.xml and maven will take care of downloading all the respective dependencies automatically. Below is the pom.xml for our project.

	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

	<name>Spring4MVCHelloWorldDemo Maven Webapp</name>



		<!-- Below declared dependencies are included for the servers who may complain about servlet/jstl missing dependency -->


The Maven plugin maven-compiler-plugin has been added here to explicitly specify the java-version we are going to use. Do note that it also force eclipse to respect the jdk-version being used for the project. if it is not present, and you perform mvn-update from within your eclipse, eclipse switches jdk-version back to 1.5 which is annoying. So do add it in your project pom as well.

Step 3: Add Controller and View

Add a package under src/main/java [src/main/java->New->package].
Then create a Controller class(shown below) which simply adds a string into model which will be accessible to the view for our example.


package com.websystique.springmvc.controller;

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

public class HelloWorldController {

	@RequestMapping(method = RequestMethod.GET)
	public String sayHello(ModelMap model) {
		model.addAttribute("greeting", "Hello World from Spring 4 MVC");
		return "welcome";

	@RequestMapping(value="/helloagain", method = RequestMethod.GET)
	public String sayHelloAgain(ModelMap model) {
		model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
		return "welcome";


Lets dig deeper:

@Controller annotation marks this class as spring bean which may handle different HTTP requests based on mapping specified on class or individual controller methods.

@RequestMapping annotation is used for mapping web requests onto specific handler classes and/or handler methods. In our case, we have applied it on class level too, which says that this class is default handler for all HTTP requests of type ‘/’. @RequestMapping have several attributes [value,method,params,..] which can be used to narrow down your mapping to more specific selection.

First method does not have any URL mapping declared, so it will inherit the mapping from mapping declared on class level, acting as default handler for GET requests. Second method (due to additional mapping declaration with value attribute) will serve the request of form /helloagain. Attribute method is used to specify type of HTTP request this method can serve. If a mapping does not include ‘method’ attribute, then that mapped controller method will server all types of request on that mapped URL.

ModelMap is a Map implementation, which saves you from old request.getAttribute/ request.setAttribute. It provides a way to set/get attributes from/to request or session.

Look at the return values from these methods. These values will be suffixed and prefixed with suffix and prefix defined in view resolver(see spring-servlet.xml further down) to form the real view file name.

Create a new folder named views under WEB-INF and add in a Simple JSP page welcome.jsp ( WEB-INF/views/welcome.jsp) which in our example will simply access the model value sent from controller.

<%@ 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">
<title>HelloWorld page</title>
	Greeting : ${greeting}

Step 4: Create Spring configuration file

Spring configuration file contains instructions for Spring to operate. Here we are going to use XML configuration but one can avoid XML configuration by using Annotation based Configuration, which will be our topic for next tutorial.

Let’s create a file named spring-servlet.xml with below content in WEB-INF folder. Note that you can name this file anything you like but be sure to declare it in web.xml (as shown further down in this tutorial).

<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<context:component-scan base-package="com.websystique.springmvc" />

	<mvc:annotation-driven />
		<property name="prefix">
		<property name="suffix">


Lets dig deeper, again

<mvc:annotation-driven /> says that we can define spring beans dependencies without actually having to specify a bunch of beans in xml or implement an interface or extend a base class or anything. For example, just by annotating a class with @Controller (as we did above) , spring will know that the specified class contains methods that will handle HTTP requests, no need to define that as a bean in xml.

<context:component-scan base-package="com.websystique.springmvc" /> tells spring to search project classpath for all classes under the package specified with base-package [com.websystique.springmvc], and look at each class to see if it is annotated with specific Spring annotations [@Controller, @Service, @Repository, @Component, etc..] and if it does then Spring will register the class with the bean factory as if you had typed in the xml configuration files.

Along with that, we have declared a view resolver which will help controller to delegate the response to appropriate view.

Now we need to specify this configuration file in web.xml, as shown below.

Step 4: Update web configuration (web.xml) file

<web-app id="WebApp_ID" version="2.4"


 <display-name>Spring4MVCHelloWorldDemo Web Application</display-name>




Things to take from here are DispatcherServlet & contextConfigLocation. DispatcherServlet is the front controller which receives each request(see the url pattern) and direct the request to appropriate controller.It is also responsible for directing the response from controller to appropriate views.

Look carefully at contextConfigLocation init-param. Thanks to this parameter, you can name your spring configuration file anything you want and place anywhere you want, even you can provide multiple files. In absence of this parameter, you are obliged to name the file as ABC-servlet.xml where ABC is the dispatcher servlet name.

That’s it. You should have following project structure by now:

Step 6: Deploy & run your application

Right click your project ->Run as-> maven install as show below:


As a result, you will see a war file under target folder

Deploy this war into a container. There are several ways to do this. In case of tomcat, put this war file inside webapp folder of your tomcat installation(tomcat/webapp), and click on start.bat file(under tomcat/bin).

To be quick, i am using a handy eclipse jetty plugin run-jetty-run to run it on jetty. Right click on your war->run as->run-jetty.

Open your browser and run.



That’s it. Next post, Spring 4 MVC HelloWorld Tutorial – Annotation/JavaConfig Example contains the Annotations based full example.

Download Source Code


If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help me improve further our learning process.

If you appreciate the effort I have put in this learning site, help me improve the visibility of this site towards global audience by sharing and linking this site from within and beyond your network. You & your friends can always link my site from your site on www.websystique.com, and share the learning.

After all, we are here to learn together, aren’t we?

  • Pingback: newtube sirius618 abdu23na716 abdu23na57()

  • I am not sure why I am getting below error when I put one more file along with index.jsp. I have mentioned the file name in welcome-file-list.

    My web.xml

    Counter Web Application








    My servlet.xml

    <!– –>


    <!– .html –>

    My Controller
    public class MainController {
    public String home(ModelMap model){
    model.addAttribute(“greeting”, “Hello World from Spring 4 MVC”);
    return “welcome”;

    public String sayHelloAgain(ModelMap model) {
    model.addAttribute(“greeting”, “Hello World Again, from Spring 4 MVC”);
    return “welcome”;

    In webapp folder, When I put home.html along with index.jsp then I get error when I remove it, it works fine.

    Thanks in advance.

  • Shibink Nlr

    It showing error message as Could not resolve archetype or.apache.maven.archetypes:maven-arhctype-webapp: 1.0 from any of the configured repositoriesries,Project creation is failed,……Just help me to create project

  • Sarunyoo Keawsopa

    Thank you for start spring mvc.

  • Narasimha Rao Konjeti

    I am not able to install the same in weblogic, can you please suggest, if I am missing anything here. thanks in advance.

  • nikhil mone


    I am facing this issue after following your steps :

    > org.springframework.web.servlet.PageNotFound noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/SpringMVCAnnotation/helloagain] in DispatcherServlet with name ‘dispatcher’

    • websystique

      Hi Nikhil, did you first build the project? Please follow Setup Tomcat+Eclipse if you face any issue.

  • Tapan Yawalkar


    Can you tell me how to use the jetty plugin to run the web application..I tried but its not working for me

  • Rajender Singh

    need to have one extra xml file to keep jdbc bean. where will be placing them in such folder structure.

    • websystique

      Hi, It should be Along side spring-servlet.xml.

      • Rajender Singh

        after putting springconfiguration file along side spirng-servlet/xml getting this error

        ERROR [org.springframework.web.servlet.DispatcherServlet] (MSC service thread 1-5) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘spring4Controller’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.til.et.Implementation.BusinessLogic com.til.et.spring4.Spring4Controller.functions; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.til.et.Implementation.BusinessLogic] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

        beans defined in spring configuration files are not getting created.

        • websystique

          Please make sure that you have the missing bean [ BusinessLogic].

  • Mohammed Reda Berrohou

    Thank You THis is one of the best tutorial on spring mvc across the web :)

  • tjm1706

    Thank you for the tutorial series on Spring MVC.
    When starting the Tomcat … I get the “Hello world” page.
    When I type http://localhost:8080/Spring4MVCHelloWorldDemo/helloagain … then I get a 404..
    I had installed the newest Tomcat. And I checked it with via the link you provided.
    Can you help solving this?

    • samyak bhalerao

      I am facing same issue .Event after doing ‘project’>’clean’ it didn’t worked out. Please provide some direction.

      • saurabh kachhia

        That is might be because you put your Controller class in default package(i.e. No package). I resolved the same error by creating a package and put my Controller class in it. Also specify your package name in the base package of spring-context.xml file.

  • Jmp Jmp

    Excellent, Able to run in single shot.

  • AKHIL mohanan

    Good example.
    works fine

  • vani

    how to add a filter configuration in spring4

    • websystique

      Hi Vani,

      With Java Configuration, You can override following method in your initializer class [ from AbstractDispatcherServletInitializer], also available in AbstractAnnotationConfigDispatcherServletInitializer:

      protected Filter[] getServletFilters() {
      //return null;
      return new Filter[]{new MyFilter()};
      where MyFilter is your filter class.

      For XML, You can use DelegatingFilterProxy. Have a look at this post, which explaines it very well.

  • jaison steephen

    I am able to run application successfully. But faced one issue.. project have by default one index.jsp. only after deleting that file from the project structure,, I got the expected result…. still that time, I was getting “Hello World!” in index.jsp.. It means servlet mapping was not happend in web.xml, till I deleted index.jsp.. Do u have any idea,, why application behaved like that? thanks in advance

    • JMmak

      You can add this to your web.xml file:

  • Mighty

    Thank you Websystique!
    Tutorial is very informative and awesome!

  • Arnish Gupta

    Hello, My project is working properly but output is show ${greeting} same not print the value that initialize in controller.

  • Mel Flo

    thanks so much for this tutorial!!!!!!

  • Aline Santos

    When I create a Maven project, I don’t have the same structure as you did: “src/main/java” is not automatically created, so I can’t go on exactly as the tutorial because my folders are different… I’m using Eclipse Mars, could this be the cause of this difference?

    • websystique

      Indeed, by default folder ‘src/main/java’ is not created automatically (when using maven-archtype-webapp). To do that, select folder ‘main’ in folder tree (in the next half of project), and create folder java in it. Refresh your project in eclipse and that’s it. You will see both ‘src/main/java’ & ‘src/main/resources’ as sources. You can also add test folders in similar way. Your Eclipse itself is not really a problem.

      • Aline Santos

        Thank you very much! And sorry for my lack of knowledge

  • Pingback: Spring4 + WildFly | Flat tire()

  • Pingback: Vanessa Smith()

  • Pingback: Peter Smith()

  • Pingback: займ на банковскую карту()

    • websystiqueadmin

      Dear User, Thanks a lot for you comment. I really appreciate it.

      Please feel free to visit other posts on this blog.

      WebSystique Admin

  • Pingback: займ на карту()

  • Pingback: Gregory Smith()

    • websystiqueadmin

      Thanks a lot for your feedback. Feel free to explore other posts on this blog and letting me know if any improvement required.

      Thanks again…
      Websystique admin

  • Pingback: Spring 4 MVC HelloWorld JavaConfig Example - WebSystique()