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 Spring MVC 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.



340 Comments

  • Syed 23 April, 2013, 19:22

    i am running this application in tomcat 6 but getting 404 error after clicking on Say hello

    • Gaurav 26 April, 2013, 12:13

      It won’t work with tomcat 6. Use tomcat 7 . It will work then.

    • Rishab 1 May, 2013, 17:22

      Have you mentioned the base package correctly in spring-servlet.xml file.

  • Rakesh 24 April, 2013, 16:28

    I got error

    Error creating bean with name ‘viewResolver’ defined in ServletContext resource

  • algiogia 25 April, 2013, 13:45

    Maybe you could explain where to get jstl-1.2.jar and commons-logging.jar, cause they are not in the Spring package…

  • algiogia 25 April, 2013, 16:08

    So, for those getting an empty page after clicking “Say hello”

    be sure you import

    ModelAndView

    from

    org.springframework.web.servlet

    and not from

    org.springframework.web.portlet

    !

  • Lucas Gladki 30 April, 2013, 15:35

    If someone still has an issue after clicking ‘say hello’ saying ‘servlet unavailable’
    download jstl.jar and make sure it is in WEB-INF/lib
    here is the link:
    repo1.maven.org/maven2/javax/servlet/jstl/1.2/jstl-1.2.jar

  • Balan 1 May, 2013, 4:22

    Help::
    This is what comming up. Why?

    type Status report

    message /Spring3MVC/

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

    • danish 3 June, 2013, 13:29

      I am also getting the same error. Please suggest.

  • Rajlaxmi 15 May, 2013, 14:38

    Hi Syed..

    you are getting 404 error, because in this example, jsp pages are kept in ‘WEB-INF’ folder, ideally we should keep pages in ‘WebContent ‘ directory.

  • hii 30 May, 2013, 22:23

    If anyone face any error while running then
    kindly change your view resolver to InternalResourceViewResolver in application-context
    thanks

  • niet 31 May, 2013, 9:47

    Nice tutorial.. easy to understand for newbie at spring mvc like me.. :D thanks

  • eugene 3 June, 2013, 16:21

    hi guys, i am new to j2ee and spring. this tutorial has been a great read for newbies like me. however, i have some problems understanding this part of the tutorial. please do guide me should my understanding is not correct. i have understand it like this:

    run application > index.jsp (welcome page) > click link (direct to hello.html) >
    go to web.xml > read url mapping (*.html) > servlet name being spring > go to dispatcherservlet > dispatcherservlet reads spring-servlet.xml > scan package controller >
    dependency injection to view resolver > reads the properties of this view resolver >
    assign property names to values > dispatcherservlet reads view resolver > assigns @requestMapping(/hello) in between prefix and suffix > now call /WEB-INF/jsp/hello.jsp > hello.jsp reads $(message) and resolver rendering this jsp to user > finish

  • Girish 3 June, 2013, 18:24

    Hi viral i am getting error 404 after clicking say HEllo,and there is no error in serverlog,i am trying to run code given on page to download

  • Girish 3 June, 2013, 19:00

    Sloved 404 error after clicking sayhello by replacing this in web.xml

    spring
    /

  • Andy Kang 7 June, 2013, 2:35

    Beautifully done! Highly recommend it to anyone who would like to learn the basics of Spring MVC

    Thank you so much!

  • Muskaan Sharma 10 June, 2013, 14:29

    Sir, Tutorials are very easy to understand but When I run application I found error in my PC

    SEVERE: StandardWrapper.Throwable
    java.lang.NoSuchMethodError: org.springframework.core.io.ResourceEditor.(Lorg/springframework/core/io/ResourceLoader;Lorg/springframework/core/env/PropertyResolver;)V
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:123)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1189)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1103)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1010)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4915)
    at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5242)
    at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5237)
    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:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
    SEVERE: Servlet.service() for servlet [jsp] in context with path [/Spring3MVC] threw exception with root cause
    java.lang.NoSuchMethodError: org.eclipse.jdt.internal.compiler.Compiler.(Lorg/eclipse/jdt/internal/compiler/env/INameEnvironment;Lorg/eclipse/jdt/internal/compiler/IErrorHandlingPolicy;Lorg/eclipse/jdt/internal/compiler/impl/CompilerOptions;Lorg/eclipse/jdt/internal/compiler/ICompilerRequestor;Lorg/eclipse/jdt/internal/compiler/IProblemFactory;)V
    at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:442)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:374)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:352)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:339)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:594)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:344)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

    Please Suggest me Why it Comes…
    Thanks

    • Jaskirat Singh 14 June, 2013, 9:00

      U need to include all the jar file in the Lib folder inside the WEB-INF for Spring 3.0.0 + common logging and jstl correctly

  • Jonathan 14 June, 2013, 4:29

    if you all still have 404 errors then :

     
    change entry in web.xml to  :
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>/</url-pattern>
     
  • vijay 17 June, 2013, 15:47

    I am getting following error after clicking on say Hello.

    type: Status report
    message: Servlet spring is not available
    description: The requested resource (Servlet spring is not available) is not available.

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]