Spring 4 MVC Hello World Tutorial – Full Example

76 Flares Twitter 0 Facebook 32 Google+ 40 LinkedIn 4 Filament.io 76 Flares ×

Table of Contents

  1. Technologies Used
  2. Project Setup using Maven
  3. Spring Bean Configuration
  4. Web App Configuration
  5. Developing the Controller
  6. Developing the View
  7. Running using browser
  8. Using Java Config instead of XML

In this tutorial you will learn how to develop a Spring 4  MVC Hello world example. Hope this tutorial will give you a quick start in Spring MVC development using the latest Spring 4 Release.

Technologies used:

  1. Spring 4.0.1.RELEASE
  2. JDK 1.6
  3. Maven 3
  4. Eclipse Java EE IDE ( Eclipse JUNO)

Updates (10 -Feb -2014): Updated the tutorial with JavaConfig. Now explains how to use WebApplicationInitializer and @Configuration 

1: Maven Project Setup In Eclipse

Let us start with the creation of  a Maven web project in Eclipse. A maven web project archetype will create all the necessary folder structures required for a web project. We assume that you have installed the maven plugins for Eclipse. If you haven’t configured it, refer our earlier Spring tutorial that has section explaining how to setup maven in eclipse.

File ->  New  -> Other -> Maven -> Maven Project

Maven Project Eclipse

Click Next and Click Next again ( If you wish to change default Workspace location , you may do so). In the next screen you should pick the maven web app archetype. Refer the screen below

Maven Web App Archetype

Click Next  and provide the following values

  1. GroupId :com.javahash.web ( you can change this according to your package structure)
  2. Artifact Id: Spring4MVCHelloWorld
  3. Version: 1.0-SNAPSHOT

Click Finish to complete the Project Setup.

Project Structure-SpringMVC

This completes the project setup. Make sure the project is loaded in eclipse.

2:  Spring Configuration

Activities in this section can be broadly defined as

  1. Adding Spring libraries as dependencies in pom.xml
  2. Defining an XML file that holds the configuration for spring beans
  3. Configuring web.xml

Spring libraries are added as dependencies in maven (pom.xml).

Dependencies – pom.xml

2.1 Configuring Spring Beans (dispatcher-servlet.xml)

Create an XML file and name it dispatcher-servlet.xml. This configuration file can be given any name. We are using the name dispatcher-servlet.xml for this project. Place this file inside the WEB-INF folder. This xml file holds the configuration info for the view resolver that spring uses to map view names to a concrete view files.

Above piece of code instructs spring to scan the package (com.javahash.spring.controller) and its children to detect and auto configure components. For instance, we can annotate a class with @Controller annotation and spring will automatically configure it as a controller class. Due to this auto scanning feature, there is no need to configure controller classes in xml files.

3: Configuring web.xml

The  org.springframework.web.servlet.DispatcherServlet acts as the front controller for the application. All requests are intercepted by the spring servlet.

Note: Location of web.xml is inside the WEB-INF Folder

The default rule is spring looks for a file honoring the contract , servletname-servlet.xml to load the spring configuration beans. Because of this, spring will look for the file ( dispatcher-servlet.xml). If we had used a different name for the servlet, say frontcontroller, then the framework will look for a file with name frontcontroller-servlet.xml to load MVC configurations. We can override this behavior by explicitly specifying the mvc configuration file using the parameter contextConfigLocation. We have used that in the above web.xml

4: Developing the Controller

Starting with Spring 3, there is excellent support for annotations. We can use annotations to mark our class as a controller. The HelloWorldController is a very simple controller that just echoes a message. It takes a parameter and just echoes it.

Please note the use of @Controller and @RequestMapping . The URL takes a parameter with name “name”.

5: Developing the View

Create a file named helloword.jsp inside WEB-INF/views folder.  In the dispatcher-servlet.xml, defined in section 2.1, we have specified that the jsp files will be put inside the WEB-INF/view folder.

At run-time, spring will choose the appropriate .jsp file based on the view-name returned by the controller method.

6: Build and Package

Right click the project , RunAs -> maven install

This will compile, package and install the executable as a WAR file. You can also perform maven package instead of maven install. Spring4MVCHelloWorld.war will be generated inside the target folder.

Deploy this WAR file to Tomcat web server or any web server you are using.



How to Avoid XML Files and use JavaConfig

Maintaining configuration using XML has its advantages and disadvantages. If you are not a fan of XML configuration and wish to enjoy the benefits of annotations based configuration, you can do so easily in Spring. It is your choice to go the XML path or the JavaConfig path. JavaConfig is a cool approach and helps in rapid application development and provides easy maintenance. When the number of artifacts in the project increases, JavaConfig is very handy. Also it is the developer friendly means of handling configuration. Let us see how we can replace the dispatcher-servlet.xml and the Spring Configuration defined in the web.xml to  Java classes using JavaConfig.

Replacing dispatcher-servlet.xml with Java File

Moving Spring Configuration from web.xml to WebApplicationInitializer

Download Source Code

Download – Project Source Code

Good Video Tutorial – Spring MVC



Spring 4

  • Cool tutorial. I think about learning Java/Spring about a year. It is really cool.

  • Matthieu Bertin

    Why did you choose to use xml files for the configuration?

    • I have updated the tutorial with JavaConfig also. It is up-to the developer to choose which way they want to go. I have outlined both approaches in this update.

      • Anonymous Human

        If we go the JavaConfig route, what do we name the two configuration files and where in the project directory structure do we place them in the Eclipse IDE?

  • Edgar Miguel Mamani Condori

    Where do I find javax.servlet.ServletRegistration.Dynamic?

  • Douglas Crews


  • dev

    I am not sure how were you able to run your code, you specify the version of spring as 4.0.1; however your xml context file says spring-beans 3.0 version…

    • That is the XML schema definition. It will work with spring 3 and 4.

  • Bogdan Marian Oloeriu

    This is confusing for someone new to spring. Can you please split this
    in 2 related tutorials? One based on xml configuration and one based on
    java configuration. I’m not able to see what file goes where in what
    package or folder and how the final project structure should look like.

  • Chris Kalubi

    My IDE (intelliJ) doesn’t recognize the register() method int the webInitializer class:
    it’s strange because I have spring-web.jar in my dependecies.
    Do you know why?

  • ahmed abbas

    very helpful thanks

  • Brandon

    Hi there, Is it possible for you to provide a link for the code to be downlaoded?

    • I will provide the code in a week. Right now I am out of station and once iam back I will provide you the full code.

      • The article is updated with the link to download the complete project source code.

  • sandeep singh

    Hi ,
    Is it possible for you to provide a link for the code to be downlaoded?

    • Complete project source code is now available. Please check the Download section of the article.

      • sandeep

        thnx 4 source code.
        “http://localhost:8080/Spring4MVCHelloWorld/” is working
        but whn I fired “http://localhost:8080/Spring4MVCHelloWorld/hello/?name=JavaHash” URL that is not working it gives me 404 error.

        • DBspringing

          remove the / before the ?

  • DBspringing

    I swapped the xml for JavaConfig. Now when I run the output on the browser is

    Hello : ${name}

    What am I missing?

    • jaycuse

      I have the same problem.
      I added jstl dependency but doesn’t solve the problem
      jstl jstl 1.2

    • sn.

      I still have the same problem. Have you found any solution to it?

      Thanks in advance.

    • Felipe Drequeceler Pinto

      are you using the correct URL?
      ?name=JavaHash at the end1http://localhost:8080/Spring4MVCHelloWorld/hello/?name=JavaHash

    • kas

      It may be caused by wrong doctype of web.xml, try to change it to simple

      • kas

        editor cut the code “to simple ? xml version=”1.0″ encoding=”UTF-8″ ?” with tags around.

        • Nico Cortés

          The problem was inside the web.xml file.
          Changing the header as Kas told us, and it’ll work.
          Thanks Kas.

        • Ashish

          Thanks Kas… I had the same problem too.. 🙂

  • Seetesh

    Does this code run on JBoss 7.1.1? Pls try to deploy it as most of us wont use Tomcat to deploy the same. Besides you have not mentioned which
    Tomcat version it has been tested.

    • It should run on jboss. There is nothing tomcat specific in the code. Use maven to build the project and add all dependencies in pom.XML. I used Tomcat 7

  • Rex Rao

    Does this code work on JBoss 7.1.1?

    • It is just spring and jsp.it should work in jboss.

  • Sherlock Ouyang

    Hi there, thank you, the tutorial is very helpful. But I got a problem while trying to run your source code on eclipse, I chose to “run on server” but it said
    “Could not publish to the server.

    I am a green hand, could you tell me why and what to do to solve this problem ?Thanks again.

  • Saad

    This as a great tutorial !! Thanks.
    Could you please do an extension on this on how to easily map from controller to views. (convention over configuration). Say I want to create a folder for each controller in the “views” folder and map each action to the specifig jsp file.

  • Sandip Bhaumik

    I am getting error on SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener

    java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

    But I can see that spring-web[version] present in my classpath. Tried cleaning few times but still no luck.


  • Roland

    The tutorial has some points that should be improved:

    * The generated pom.xml contains an url element, which refers to maven.apache.org. This is wrong, since this project does not have a homepage at all. The element should be removed.

    * The pom.xml is neither indented correctly nor are there useful paragraphs in it. For example, there should be an empty line before and after the “properties” element.

    * JUnit 3.8 is outdated; for a modern example JUnit 4.12 should be used.

    * The file name “dispatcher-servlet.xml” is not arbitrary. It must correspond to the “servlet-name” in web.xml.

    * The many empty lines in the “dispatcher-servlet.xml” are not necessary.

    * In dispatcher-servlet.xml the “property” elements can be written shorter; they should be properly indented.

    * The web.xml uses the DTD for version 2.3 but declares a webapp with version 2.4; these versions should be the same.

    * The tutorial does not mention where exactly each of the example files has to be placed.

    * In helloworld.jsp there is a cross-site scripting vulnerability.

    • Lucky

      How can I prevent the cross-site scripting vulnerablity?

  • Carlos Barros

    thanks to spring guys now we are obligated to use maven, a hard and complex tool only for build helloworld applications like that… thats why a lot of new programers are moving to other technologies not so burocratic and much more eficient.
    yes I really hate maven most of times. the customer dont pay us to configure and setup tools but to effectively build software. maven force us infinite time consuming setups!

    • Miguel

      Maven makes dependency much easier. Also the archetypes generation save me lot of time.

      • Johaness

        I´m here for learning SPRING not MAVEN. most projects simply doesn’t use it due to complex infrastructure needed.

    • ∆ [c0d3r28] ∆

      “a hard and complex tool”

      I think perhaps you need to do a little more Maven homework, its a pretty straight forward and powerful build tool. Of course you dont have to use Maven, you can build it manually or with other build tools like Gradle. Maven is just the widest used because it is the easiest and works well with Spring.

      • Johaness

        its a lack of focus. Maven is not Spring, we are here to learn Spring not for learning maven! its not easy…

        • ∆ [c0d3r28] ∆

          Well, its a common practice to use a build system to build the project. Maven handles all the spring dependencies, no need to go and get them manually download them, add them to the project etc.

          It’s pretty hard to find a spring tutorial that doesn’t include some build system. Spring has been architectured to fit in with build systems, so Id say a Maven overview is pretty justified here, since its a popular build tool.

          However, this is far from the best tutorial on the subject.

  • Tony

    the biggest flaw with this tutorial is it never mentions where the web.xml and configuration files should be saved. Without this information, it’s no better than useless.

    • You should put web.xml and the dispatcher-servlet.xml in the WEB-INF Folder

  • newbies

    I have been searching for 10 hours and this is the only example that works out-of-the-box. Many thanks. Great job!

  • sam

    I am not able to see hellow word on Hello.jsp i used view resolver

    • Ashish

      Same with me

  • tracksie

    eh? this was all doable in Spring 3 too. This tut doesn’t use any new goodness from Spring 4!?!

  • raju

    1 salute 2 u sir ji. after 15 days of problematic approach today only i got up with ur solution. it’s really nice that it’s working. i feel that i have done something(troubleshooting). having a inner happiness feeling

  • stevematdavies

    Dear oh dear, what a mess of a tutorial!

  • BAKRI Anouar

    the correct namespace and schemalocation for mvc-dispatcher-servlet.xml

  • BAKRI Anouar

    the correct namespace and schemalocation for web.xml

  • GG

    Awesome tutorial. Thanks 🙂

  • ∆ [c0d3r28] ∆

    “Deploy this WAR file to a web server , say Tomcat and issue”

    Ok, any chance you can run through this as there are a few steps involved, such as adding a server, setting up the project to run with the server and how to deploy the WAR?????

  • ∆ [c0d3r28] ∆

    Further investigation into this tutorial reveals quite many errors, and missing dependencies, such as java version, maven java version export dependencies. This is actually a now outdated and incorrectly configured project, and it appears as if the Author has not updated it. I will look elsewhere for a better provided tutorial, one that uses the Spring Tool Suite (sts) where the correct defaults are provided.

    To the Author whilst I appreciate the effort, I suggest you rethink this tutorial and update it with many of the corrections suggested in the comments, and a good look at the latest Spring Build

  • Abhijeet Shukla

    Where to place controller ? Cant we run it directly from Eclipse without manually running from Tomcat ?

  • Abhijeet SHukla

    worst example I have came across, find an actually understandable and working example here https://spring.io/guides/gs/maven/

  • Java Pro

    this article is well explain and must visit this also