Simplest Spring MVC Hello World Example / Tutorial – Spring Model – View – Controller Tips

Do you have any one of below question?

  • Developing a Spring Framework MVC 4 application step-by-step..
  • java – Spring MVC tutorial from the scratch
  • Spring MVC Fast Tutorial
  • Spring MVC Framework Tutorial
  • First Spring MVC application tutorial
  • Spring 4 MVC Tutorials, AJAX Demo, jQuery Demo, JavaScript Demo, Tips & Tricks Spring 4 MVC

Then you are at right place. Here I’ll demonstrate simple Spring MVC framework for building web applications.

[updated: 10/19/2014] Scroll down for all detailed steps.

First thing first. I’m using below tools which you may need to download if you don’t have already.

  1. Tomcat 7.0.56 (Download link)
  2. Eclipse IDE Luna Service Release 1 v4.4.1(Download link)
  3. Spring 4.1.1 (No download required)
  4. JDK 1.7 (Download link)

Main goal for this tutorial to create Spring MVC Application in the simplest way. This is how our application result will look like. This is a final result once you complete all below steps.

Welcome page ==> index.jsp

CrunchifySpringMVCTutorial index.jsp page Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Result returns from Controller Class icon smile Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Message Coming from Controller Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Now Let’s get started

Step 1.

Open Eclipse and Create Dynamic Web Project CrunchifySpringMVCTutorial.

Create Dynamic Web Project in Eclipse Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Crunchify Spring MVC Example Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Step 2.

Use Target Runtime as Apache Tomcat 7.0

Step 3.

Convert Project to Maven Project to add all required Spring MVC dependencies to project.

Steps: Right click on project -> Configure -> Convert to Maven project.

Convert CrunchifySpringMVCTutorial to Maven project Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Step 4.

Add below jar dependencies to project.

Srping MCV Dependencies Crunchify Spring Tutorial Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Here is my pom.xml file.

Step 5.

Create Spring Configuration Bean file. /WEB-INF/crunchify-servlet.xml

In the above crunchify-servlet.xml  configuration file, we have defined a tag <context:component-scan> . This will allow Spring to load all the components from package com.crunchify.controller  and all its child packages.

This will load our CrunchifyHelloWorld.class . Also we have defined a bean viewResolver. This bean will resolve the view and add prefix string /WEB-INF/jsp/  and suffix .jsp to the view in ModelAndView. Note that in our CrunchifyHelloWorld class, we have return a ModelAndView object with view name welcome. This will be resolved to path /WEB-INF/jsp/welcome.jsp .

Step 6.

Map Spring MVC in /WEB-INF/web.xml file.

NOTE: if you don’t see web.xml file in your “dynamic web project” then follow these steps.

The above code in web.xml will map DispatcherServlet with url pattern *.html. Also note that we have define index.jsp as welcome file.

One thing to note here is the name of servlet in <servlet-name> tag in web.xml. Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml  in WEB-INF folder of web application. In this example, the framework will look for file called crunchify-servlet.xml.

Step 7.

Create Controller Class.

  • Package: com.crunchify.controller
  • Filename: CrunchifyHelloWorld.java

Create Spring Controller Class CrunchifyHelloWorld Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Note that we have annotated the CrunchifyHelloWorld class with @Controller and @RequestMapping("/welcome"). When Spring scans our package, it will recognize this bean as being a Controller bean for processing requests. The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /welcome in the URL path. That includes /welcome/* and /welcome.html.

The helloWorld() method returns ModelAndView object. The ModelAndView object tries to resolve to a view named “welcome” and the data model is being passed back to the browser so we can access the data within the JSP. The logical view name will resolve to /WEB-INF/jsp/welcome.jsp . Logical name “welcome” which is return in ModelAndView object is mapped to path /WEB-INF/jsp/welcome.jsp.

The ModelAndView object also contains a message with key “message” and Detailed value. This is the data that we are passing to our view. Normally this will be a value object in form of java bean that will contain the data to be displayed on our view. Here we are simply passing a string.

Step 8.

The View: Create /WebContent/index.jsp and /WebContent/jsp/welcome.jsp  file

After everything this is how your workspace should look like.

CrunchifySpringMVCTutorial by Crunchify Eclipse Package Structure Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Step 9.

Deploy project to Apache Tomcat and start tomcat.

Start Tomcat Server Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Step 10.

Visit: http://localhost:8080/CrunchifySpringMVCTutorial/ and you are all set.

Hurrey.. Now you know Hello World Spring MVC 4 Example. Let me know if you encounter any exception while running this.  There are lot more example you can find here.

Have anything to add to this article? Please chime in and join the conversion.
twitter Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tipsfacebook Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tipsgoogle Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tipspinterest Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tipstumblr Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tipsbuffer Simplest Spring MVC Hello World Example / Tutorial   Spring Model   View   Controller Tips

Enjoyed this post?

Be sure to subscribe to the Crunchify newsletter and get regular updates about awesome posts just like this one and more! Join more than 8000 subscribers!

  • krushnat

    I have created a spring mvc application. I have used external CSS but apache is saying that noPageFound for this XYZ.css

    • http://crunchify.com/ Arpit

      Hi Krushnat – this seems like CSS loading issue at client side. You don’t have to include it in at server side.

      • krushnat

        Thanks Arpit for replying.
        but whats next then?

        • http://crunchify.com/ Arpit

          Make sure your CSS file load at client side in .html or .jsp page. You could load it in head section.

  • Lakshmi

    It worked when I changed the Web.xml to the following:

    /welcome.html

  • Roberto Testa

    HTTP Status 404 – /CruncifySpringMVC/welcome.html
    why??

    • http://crunchify.com/ Arpit

      Hi Roberto – try following above steps again. I’ve completely rewrote above tutorial with maven dependencies. Fixed couple of bugs too.

  • http://crunchify.com/ Arpit

    Also, could you please try updating your web.xml file with above file content? I’ve just modified it. Hope that works.

  • http://crunchify.com/ Arpit

    404 error is mostly related to path. Make sure you have welcome.jsp page under jsp folder.

    • Himanshu Srivastava

      Thanks. It worked after changing in web.xml

  • Shadab Quddus

    Hi arpit,don’t know why,but I am also getting 404 error.

    It is working when I did

    crunchify

    /welcome.jsp

    Which I think my controller is not working

    • http://crunchify.com/ Arpit

      Thanks Shadab. Looking at this now. Will update web.xml file above in tutorial once checked. Thanks for tips. Keep visiting.

  • calypso

    hi nice tutorial but i am getting
    “HTTP Status 404 – Servlet crunchify is not available” error why?

    • http://crunchify.com/ Arpit

      Hi calypso – as mentioned below make sure you create resource folder rather than standard new folder.

  • Sam

    HTTP Status 404 – Servlet CrunchifyHelloWorld is not available

    • http://crunchify.com/ Crunchify

      Please make sure – the resource folder needs to be created as a new “source folder” rather than just a new folder, otherwise you will get the above errors.

      • calypso

        what do u mean with “source folder” and for which folder i must do it?

        • http://crunchify.com/ Arpit

          Defining a folder full of source code to be a Source Folder is something
          that can happen in Build Path.

          -In the Package Explorer, select the project where you want the new source folder to reside.
          – From the project’s pop-up menu, select New > Source Folder. The New Source Folder wizard opens.
          – In the Project Name field, the name of the selected project appears. If you need to edit this field, you can either type a path or click Browse to choose a project that uses source folders.
          – In the Folder Name field, type a name for the new source folder.
          – If the new folder nests with an existing source folder you can check Update exclusion filters in other source folders to solve nesting. Otherwise you have to use the Java build path page (Project > Properties > Java Build Path) to fix the nesting conflict by removing other source folders.
          – Click Finish when you are done.

    • http://crunchify.com/ Arpit

      Sam – I’ve completely rewrote above project as Maven Project. Created pom.xml file and removed all manual added dependencies.. Try following all NEW steps and you shouldn’t see any issue now..

  • rehan

    Hi Sir thanx for giving awesome tutorial. i just want to ask that how can i compile this web app into .EXE file and install on another pc and run without eclipse on other computer please replay me thanks in advance.

    • http://crunchify.com/ Arpit

      Hi Rehan –
      Just export project as executable .jar and you should be all good. Just run your executable jar project with

      java -jar projectName.jar

  • http://codersnook.com/ David McMonigle

    Arpit, do you have a tutorial for setting up Spring? I tried following the new Spring setup but it’s using Maven and I might not have that setup properly. Any starter tutorials?

    • http://crunchify.com/ Arpit

      Hey David –
      I’m in process of writing Spring MVC tutorial – just fundamentals on Spring MVC. Will be out within a week.

  • Max

    Hello,

    I get 404 on welcome page.

    With this warning : WARNING: No mapping found for HTTP request with URI [/CrunchifySpringMVC3.2.1/welcome.html] in DispatcherServlet with name ‘crunchify’

    • http://crunchify.com/ Arpit

      Hi Max –
      Could you bundle your eclipse project and send me? Would like to debug it at my end.

      • Joe

        Im getting this error when I run the app 404.

        Description Resource Path Location Type
        The servlet mapping “crunchify” refers to a servlet that is not defined web.xml /CrunchifySpringMVC3.2.1/WebContent/WEB-INF Unknown Web Problem

        • http://crunchify.com/ Arpit

          Hi Joe –
          Could you please try cleaning project? Please let me know if it doesn’t work.

          • Luke

            Hi Arpit, I have the same error is there a solution for it?

  • Regenbogenfisch

    Thats the ONLY working example I have seen so far. ALL the others are either faulty or incomplete or both.

    • http://crunchify.com/ Arpit

      Thanks Regenbogenfisch

  • memento

    Hi, Thank you for this tutorial !

    I followed it step by step but I realized I didn’t have the following jars :
    – commons-logging-1.1.1.jar
    – jstl-1.2.jar

    Where did you get them ?

    Did you have to add them manually or not ?

    If not, it would mean that I didn’t install something properly.

    I have Ubuntu 13.04 with :

    – Eclipse IDE for Java EE Developers 4.3.1 (more recent than yours)
    – Apache Tomcat 7.0.50
    – Spring 3.2.1
    – The last OpenJDK (OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4) to be precise)

    Thanks in advance.
    Greetings from France.

    • memento

      Shall I install any plugin in eclipse ?

      • http://crunchify.com/ Arpit

        Hi Memento –

        You could download those from here:
        1. Common-Logging: http://commons.apache.org/proper/commons-logging/download_logging.cgi

        2. jstl: http://download.java.net/maven/1/jstl/jars/

        • Dont_be_paranoid

          I would really really recommend Maven. Please use Maven, it simplifies things so much. Just type in the name of the artifact such as jstl and bang, there you have it from central repository. Infact you can also ask maven to download sources and JavaDoc for you.

          • http://crunchify.com/ Arpit

            Agree with you. Will update post in an hour with maven dependancy.

            
            
            	org.springframework
            	spring-aop
            	4.0.6.RELEASE
            	
            		
            			commons-logging
            			commons-logging
            		
            	
            
            
            
            
            	org.springframework
            	spring-webmvc
            	4.0.6.RELEASE
            
            
            	org.springframework
            	spring-web
            	4.0.6.RELEASE
            
            
  • Stealth Way

    WOW FINALLY a working tutorial file. Thank you so much.
    I have been searching the last 10 hours for a working MVC Hello World Example,

    I always got a 404 error page.

    Now it’s indeed working.
    I hope I can now find my mistake. Keep up this great work

    • http://crunchify.com/ Arpit

      Thank you.

  • ARM

    Hi,

    I have configure Java 7, Tomcat 7 and Eclipse Juno I am using for development.

    I have below error, please let m e know you have idea.

    java.util.concurrent.ExecutionException:
     org.apache.catalina.LifecycleException: Failed to start component 
    [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SpringMVC3.1]]
        at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252)
        at java.util.concurrent.FutureTask.get(FutureTask.java:111)
        at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
        at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
        at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
        at java.util.concurrent.FutureTask.run(FutureTask.java:166)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:722)
    Caused
     by: org.apache.catalina.LifecycleException: Failed to start component 
    [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/SpringMVC3.1]]
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
        ... 7 more
    Caused by: java.lang.NullPointerException
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:142)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5423)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        ... 7 more
    
    • http://crunchify.com/ Arpit Shah

      Hi ARM,

      Can you check this out? http://crunchify.com/org-apache-catalina-lifecycleexception/

      Hope it helps. I also faced this before..

      • ARM

        Hi App,

        Thanks for the response.

        I solve the issue, it was because of the old jar versions of Spring. It was 3.1XXX has an issue with this:

        Caused by: java.lang.NullPointerException
        at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java

        I replaced the jars with 3.2XXX and it works.
        Once again thanks for the response. Keep posting.

        ARM

        • http://crunchify.com/ Arpit Shah

          Awesome. Thanks for update ARM.

    • zemo

      i have the same error have u solved it?

  • Kevin

    Hi,

    Do you know how to do the same with Apache Velocity as the viewResolver?

    • http://crunchify.com/ Arpit Shah

      Hi Kevin,
      I haven’t tried it on Apache Velocity before but I guess this is the best time to play with it.. Will keep you posted.

  • amine

    very interesting tutoriel

    • http://crunchify.com/ Arpit Shah

      Awesome. Glad you like it..

    • http://crunchify.com/ Arpit Shah

      Thanks Amine..

  • http://countrysidelife.co.uk Mark

    Hi,

    Thank you ever so much for taking us into the latest wonderful Spring 3.2 via your hands on tutorial.

    Just one question: why didn’t you upgrade your web.xml from v2.5 to v3.0 which would make the whole tutorial more consistent on Spring version, right?

    Really appreciate your hard work!

    With best wishes,

    Mark

    • http://crunchify.comm Arpit Shah

      Thanks Mark for suggestion. Good point. Haven’t noticed that as my Eclipse has generated that code for me automatically. Below lines need to be updated in web.xml as per your suggestion.

      xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      id="WebApp_ID" version="3.0">
      
  • yo

    hi,
    thanks for the nice, detailed tutorial. I got my project running but on welcome page it gives 404 error. I message i get the html with tags like following.

    type Status report

    message /iYogesh/WEB-INF/jspHello.jsp

    description The requested resource is not available.

    Apache Tomcat/7.0.30

    • http://crunchify.com Arpit Shah

      Hi Yogesh,
      This shows jspHello.jsp file missing. Have you checked Eclipse Console to get any kind of Tomcat Startup Error?

    • M++

      the welcome.jsb should be in WebContent/WEB-INF/jsp/ but not WebContent/jsp/

      • http://crunchify.com/ Arpit Shah

        Thanks M++ for your suggestion. Keep visiting and happy coding.