Spring 3 MVC: Create Hello World application in Spring 3.0 MVC

Welcome to the Part 2 of Spring 3.0 MVC Series. In previous article we went through the Introduction of Spring MVC 3.0 framework, its request processing lifecycle and architecture diagram. In this article, let us create a simple Hello World application in Spring MVC 3.0.


For creating the hello world demo application, we will use Eclipse IDE.

Things We Need

Before we starts with our first Hello World Struts 2 Example, we will need few tools.

  1. JDK 1.5 above (download)
  2. Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (download)
  3. Eclipse 3.2.x above (download)
  4. Spring 3.0 MVC JAR files:(download). Following are the list of JAR files required for this application.
    • commons-logging-1.0.4.jar
    • jstl-1.2.jar
    • org.springframework.asm-3.0.1.RELEASE-A.jar
    • org.springframework.beans-3.0.1.RELEASE-A.jar
    • org.springframework.context-3.0.1.RELEASE-A.jar
    • org.springframework.core-3.0.1.RELEASE-A.jar
    • org.springframework.expression-3.0.1.RELEASE-A.jar
    • org.springframework.web.servlet-3.0.1.RELEASE-A.jar
    • org.springframework.web-3.0.1.RELEASE-A.jar

Note that depending on the current version of Spring MVC, the version number of above jar files may change.

Our Goal

Our goal is to create a basic Spring MVC application using latest 3.0 version. There will be an index page which will display a link “Say Hello” to user. On clicking this link, user will be redirected to another page hello which will display a message “Hello World, Spring 3.0!”.
spring-mvc-hello-world-screen

Getting Started

Let us start with our first Spring 3.0 MVC based application.
Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.
Dynamic Web Project in Eclipse

After selecting Dynamic Web Project, press Next.

eclipse-dynamic-web-project

Write the name of the project. For example Spring3MVC. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press Finish.

Once the project is created, you can see its structure in Project Explorer.
spring-mvc-3-eclipse-project
Now copy all the required JAR files in WebContent > WEB-INF > lib folder. Create this folder if it does not exists.
spring-3-mvc-jar-files

The Spring Controller Class

We will need a spring mvc controller class that will process the request and display a “Hello World” message. For this we will create a package net.viralpatel.spring3.controller in the source folder. This package will contain the Controller file.
spring-3-package

Create a class called HelloWorldController in net.viralpatel.spring3.controller package and copy following content into it.

File: net.viralpatel.spring3.controller.HelloWorldController

package net.viralpatel.spring3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

	@RequestMapping("/hello")
	public ModelAndView helloWorld() {

		String message = "Hello World, Spring 3.0!";
		return new ModelAndView("hello", "message", message);
	}
}

Note that we have annotated the HelloWorldController class with @Controller and @RequestMapping("/hello") on line 7 and 10. 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 /hello in the URL path. That includes /hello/* and /hello.html.

The helloWorld() method returns ModelAndView object. The ModelAndView object tries to resolve to a view named “hello” 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/hello.jsp". We will discuss this shortly how the logical name “hello” which is return in ModelAndView object is mapped to path /WEB-INF/jsp/hello.jsp.

The ModelAndView object also contains a message with key “message” and value “Hello World, Spring 3.0!”. 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.

The View: Create JSP

To display the hello world message we will create a JSP. Note that this JSP is created in folder /WEB-INF/jsp. Create hello.jsp under WEB-INF/jsp directory and copy following content into it.

File: WEB-INF/jsp/hello.jsp

<html>
<head>
	<title>Spring 3.0 MVC Series: Hello World - ViralPatel.net</title>
</head>
<body>
	${message}
</body>
</html>

The above JSP simply display a message using expression ${message}. Note that the name “message” is the one which we have set in ModelAndView object with the message string.

Also we will need an index.jsp file which will be the entry point of our application. Create a file index.jsp under WebContent folder in your project and copy following content into it.

File: WebContent/index.jsp

<html>
<head>
	<title>Spring 3.0 MVC Series: Index - ViralPatel.net</title>
</head>
<body>
	<a href="hello.html">Say Hello</a>
</body>
</html>

Mapping Spring MVC in WEB.xml

As discussed in the previous article (Introduction to Spring 3.0 MVC), the entry point of Spring MVC application will be the Servlet define in deployment descriptor (web.xml). Hence we will define an entry of org.springframework.web.servlet.DispatcherServlet class in web.xml.
Open web.xml file which is under WEB-INF folder and copy paste following code.

File: WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Spring3MVC</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>
			org.springframework.web.servlet.DispatcherServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.html</url-pattern>
	</servlet-mapping>
</web-app>

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 spring-servlet.xml.

Spring configuration file

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.

File: WEB-INF/spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:component-scan
		base-package="net.viralpatel.spring3.controller" />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

In the above xml configuration file, we have defined a tag <context:component-scan>. This will allow Spring to load all the components from package net.viralpatel.spring3.controller and all its child packages. This will load our HelloWorldController 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 HelloWorldController class, we have return a ModelAndView object with view name “hello”. This will be resolved to path /WEB-INF/jsp/hello.jsp.

That’s All Folks

You may want to run the application now and see the result. I assume you have already configured Tomcat in eclipse. All you need to do:
Open Server view from Windows > Show View > Server. Right click in this view and select New > Server and add your server details.
To run the project, right click on Project name from Project Explorer and select Run as > Run on Server (Shortcut: Alt+Shift+X, R)
spring-mvc-hello-world-screen

Download Source Code

Click here to download source code (9.05kb)

Moving On

In this tutorial we created a small Hello World application using Spring 3.0 MVC framework. Also we learned about the spring configuration and different annotations like @Controller and @RequestMapping. In next article we will see how easy it is to handle form data using Spring 3.0 MVC.



158 Comments

  • Steve Davies wrote on 23 November, 2011, 18:02

    Hi, After my own build of this project failed I tried the download, but that fails as well.
    On clicking ‘Say Hello’ I’m getting:
    HTTP Status 404 – /Spring3MVC/hello
    The requested resource (/Spring3MVC/hello) is not available.
    In the console I have the following warnings:

    WARNING: Failed to process JAR [jar:jndi:/localhost/Spring3MVC/WEB-INF/lib/order-supplemental.jar!/null] for TLD files
    java.util.zip.ZipException: zip file is empty
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.(Unknown Source) //plus about another 30 files
    WARNING: Failed to process JAR [jar:jndi:/localhost/Spring3MVC/WEB-INF/lib/order.jar!/null] for TLD files
    java.util.zip.ZipException: zip file is empty
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.(Unknown Source) //plus about another 30 files

    I’ve checked order-supplemental.jar and order.jar, and both have zero bytes.
    Any help greatly appreciated.

    • Ubbo wrote on 27 November, 2011, 6:10

      I using Glassfish server and i have the same problem. The requested resource () is not available.

  • Ken wrote on 24 November, 2011, 9:20

    Yeah, this tutorial does not work with JBoss 6 and Spring 3. I downloaded the spring deployer from http://www.jboss.org/snowdrop/downloads and selected the JBoss AS 6 with Spring 3. I followed the steps in this article but it is not working as you state above. Very frustrating for an out-of-the-box helloworld perspective. Does anyone have a solution?

  • John Avera wrote on 27 November, 2011, 2:05

    As with others, this example does not work. Very frustrating for a Hello World example. I have tried coding it manually as described in the article and downloaded the code including libraries. The project compiles, but when I click “Say Hello” which has a url of “localhost:8080/Spring3MVC/hello”, I get 404 error:

    type Status report

    message /Spring3MVC/hello

    description The requested resource (/Spring3MVC/hello) is not available.

  • Gagandeep wrote on 27 November, 2011, 13:27

    The Program will not work unless u have the required import files. such as (org.springframework.web.servlet.ModelAndView) The modelAndView is itself a class but when the above written program is executed in any IDE an error is prompted that no such class is found but instead let us create our own class “ModelAndView”. Same goes for the controller annotation.

    One may find the repositories in the spring framework distribution folder where all the jar files are already there.. (spring-framework-3.1.0.RC1\dist)

  • Jose wrote on 30 November, 2011, 4:18

    It works, thanks

  • Ken wrote on 1 December, 2011, 4:15

    Instead of going through eclipse I packaged everything into a Spring3MVC.jar file and put it in JBoss’s server/default/deploy directory. When I start up the server I see that the controller is being deployed and if I go to http://localhost:8080/spring3mvc/ I see the “Say hello” link but when I click on it I get a message that says “The requested resource (/Spring3MVC/hello) is not available” but there is no meaningful feedback from the console output to help me fix this. Any other suggestions would be helpful. Thanks, Ken p.s. My Jboss 6 is “clean” as I only installed it a week ago, and I am using the latest 3.0.6 Spring jars.

  • AA wrote on 3 December, 2011, 9:04

    this worked for me well. Thanks

  • GK wrote on 4 January, 2012, 23:23

    Add the following to your POM

    <dependency> 
         <groupId>javax.servlet</groupId> 
         <artifactId>jstl</artifactId> 
         <version>1.2</version>
    </dependency>
    

    Taken from

    http://www.mularien.com/blog/2008/02/19/tutorial-how-to-set-up-tomcat-6-to-work-with-jstl-12/

  • Ron wrote on 5 January, 2012, 11:52

    Hi Viral,

    I just came across your blog while searching for some good tutorial on Spring 3. This blog post really helped me to start with Spring 3 basics. Now I’m looking forward to explore and try my hands on next Spring tutorials on your blog. Thanks and keep writing! :)

    Regards,
    Ron

  • Christmas wrote on 10 January, 2012, 19:49

    This works greats ! Thx a lot ! You made me gain 8 work-hours. :)

  • Binhnx wrote on 11 January, 2012, 3:08

    Haft of day stay on your site is equal to a month searching :D

    • Viral Patel wrote on 11 January, 2012, 11:44

      Thanks for the kind words Binhnx :-)

  • Rimon Mikaheil wrote on 11 January, 2012, 3:12

    I found the problem with the above code. In the HelloWorldController, the value of “/hello” of RequestMapping annotation should be “/hello.html” since the request is for hello.html

    • Viral Patel wrote on 11 January, 2012, 11:47

      @Rimon: While mapping the request in Spring using @RequestMapping annotation, you just have to mention default mapping string. In our case which is /hello. And while calling the controller from browser, we need to call url /hello.html as *.html is mapped to DispatcherServlet in web.xml.

  • Hardeep wrote on 12 January, 2012, 10:05

    Hi Viral,
    Thanks for your valuables posts. it’s really appreciate able.
    I have tried this example.But I am getting some error. Could you please quide me on this.
    Issue is:
    “org.springframework.web.servlet.DispatcherServlet noHandlerFound No mapping found for HTTP request with URI [/SpringTest/hello.html] in DispatcherServlet with name ‘spring’

    Regards
    Hardeep

  • Paul Scullion wrote on 12 January, 2012, 15:04

    This demo will not work until the following line is added to the spring-servlet.xml file.

    Otherwise a 404 error will occur.

  • Paul Scullion wrote on 12 January, 2012, 15:09

    <mvc:annotation-driven/>

  • Angel Montenegro wrote on 12 January, 2012, 21:45

    Hi Viral Patel,

    I’m having the same 404 issue:

    The requested resource (Servlet spring is not available) is not available.

    Could you please help me to fix that issue? I found the tutorial very easy to follow, but I could’t fix this.

    I also tried with the code that you provided, however,it didn’t work either

    Thanks.

  • keerthi wrote on 16 January, 2012, 12:57

    i got this problem in above example
    HTTP 404 error Requested resource not found

  • sanjeewa wrote on 17 January, 2012, 11:07

    thanks …
    great tutorial .

  • fafa wrote on 17 January, 2012, 23:06

    hi vira,

    when i tried running this program. i have some error

    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

    i used maven
    pom.xml

    org.springframework
    spring-webmvc
    3.0.1.RELEASE

    can you help me to solved my errors !

  • Ben wrote on 20 January, 2012, 4:26

    Hi guys, when I run the downloaded code I can see the “say hello” link but when I click the link this is the error I get:

    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_20\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:\Program Files\Windows Resource Kits\Tools\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files\PHP\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;c:\maven3\bin\;c:\php;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Sun\SDK\bin;C:\Ruby192\bin;
    Jan 19, 2012 5:54:21 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:Spring3MVC’ did not find a matching property.
    Jan 19, 2012 5:54:21 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Jan 19, 2012 5:54:21 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 654 ms
    Jan 19, 2012 5:54:21 PM org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    Jan 19, 2012 5:54:21 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
    Jan 19, 2012 5:54:21 PM org.apache.catalina.core.ApplicationContext log
    INFO: Marking servlet spring as unavailable
    Jan 19, 2012 5:54:21 PM org.apache.catalina.core.ApplicationContext log
    SEVERE: Error loading WebappClassLoader
    context: /Spring3MVC
    delegate: false
    repositories:
    /WEB-INF/classes/
    ———-> Parent Classloader:
    org.apache.catalina.loader.StandardClassLoader@1b90b39
    org.springframework.web.servlet.DispatcherServlet
    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1128)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Jan 19, 2012 5:54:21 PM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /Spring3MVC threw load() exception
    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1128)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)

    Please help!

  • Ben wrote on 20 January, 2012, 4:49

    FInally reduced the error to this below by added all the jars needed:

    an 19, 2012 6:16:49 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/Spring3MVC/WEB-INF/jsp/hello.html] in DispatcherServlet with name ‘spring’

    my question is hello.jsp is not “.html” where is the .html file as in the viewResolver?

  • Ben wrote on 20 January, 2012, 20:57

    Guys, I got the same errors you guys were getting….u need to add some additional jars file as shown in the error logs and also update the spring-servlet.xml

  • Ben wrote on 20 January, 2012, 21:22

    But unfortunately when I click on the Say hello link it is not able to redirect to hello.jsp but when I enter the url http://localhost:8080/Spring3MVC/hello.html it work fine….

    any help guys??

    • Viral Patel wrote on 20 January, 2012, 21:31

      Can you check where “Say hello” link is pointing too. It must be the same URL that you trying to reach manually.

      • Sale wrote on 22 January, 2012, 22:19

        Somehow I have the same problem like Ben. It works perfectly when I add suffix .html on the links
        but hello alone does not work

        • Sale wrote on 22 January, 2012, 22:21

          ooookkkkk, now i got it. I have used Click here to download source code (9.05kb) link, and there the index.jsp points to hello instead of hello.html like it is in the tutorial.

  • Roose wrote on 23 January, 2012, 9:14

    Jan 19, 2012 5:54:21 PM org.apache.catalina.core.ApplicationContext log
    SEVERE: Error loading WebappClassLoader
    context: /Spring3MVC
    delegate: false
    repositories:
    /WEB-INF/classes/
    ———-> Parent Classloader:
    org.apache.catalina.loader.StandardClassLoader@1b90b39
    org.springframework.web.servlet.DispatcherServlet
    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)

    To resolve this error pls add spring-webmvc-2.5.6.jar.

  • Suhas wrote on 24 January, 2012, 10:07

    Worked well for me. Great explanation as well. Thanks a lot, Viral.

  • Carlos wrote on 27 January, 2012, 10:11

    It works!!! thanks for your tutorial. It didn’t work at the begining, but I’ve learned a lot, even more, looking for a solution the problems. I’ m going to the next part. Thanks.

  • Veasna wrote on 31 January, 2012, 11:04

    It is fantastic lesson, thanks.
    But i have problem with ${message} which is nothing show on the web page.
    any idea, please!!!!

  • Anoop wrote on 1 February, 2012, 11:34

    I managed to resolve the 404 error by adding 2 more jar files .. viz;
    http://www.docjar.com/jar_detail/jstl-1.1.2.jar.html
    http://www.docjar.com/jar_detail/commons-logging-api-1.0.4.jar.html

    hope it helps

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Copyright © 2012 ViralPatel.net. All rights reserved.