Spring MVC Fast Tutorial: Hello World

How Spring MVC works

Basically the same way as Struts:

  • Based on the HTTP request URL, the DispatcherServlet calls the corresponding Controller.
  • A View is rendered and sent as HTTP response.

Spring Servlet Declaration

In 'WEB-INF/web.xml', we declare Spring DispatcherServlet and map '*.html' URLs to it:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
 
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
 
  <welcome-file-list>
    <welcome-file>
      jsp/index.jsp
    </welcome-file>
  </welcome-file-list>
 
</web-app>

Spring Servlet Configuration

Let's now create the Spring configuration file 'WEB-INF/springmvc-servlet.xml' (name based on the servlet name above):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
  <bean name="/hello_world.html" class="springmvc.web.HelloWorldController"/>
 
  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
      <property name="prefix" value="/jsp/"/>
      <property name="suffix" value=".jsp"/>
  </bean>
 
</beans>
  • Map URL /hello_world.html to Controller HelloWorldController
  • Declare View Resolver: when view 'view_name' is called (from the Controller), the file '/jsp/view_name.jsp' will be used.

Controller

Let's create the Controller 'WEB-INF/src/springmvc/web/HelloWorldController.java':

package springmvc.web;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
public class HelloWorldController implements Controller {
 
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
 
		String aMessage = "Hello World MVC!";
 
		ModelAndView modelAndView = new ModelAndView("hello_world");
		modelAndView.addObject("message", aMessage);
 
		return modelAndView;
	}
}

This Controller calls the view 'hello_world', passing 'message' to it (like a Struts attribute).

View

Now the view: 'jsp/hello_world.jsp':

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
	<p>This is my message: ${message}</p>
</body>
</html>

Displays the message attribute previously set in the Controller.

Make it work

From 'WEB-INF' folder type

ant

Relaunch Tomcat and check it's working: http://localhost:8180/springmvc/hello_world.html

Summary

Your project should now look like that:

You can download it here. With Java 6, delete the class files (ant clean) before compiling (ant).

  • We declared Spring servlet in web.xml
  • We created a Spring configuration file where we mapped an URL to a controller and defined a way to resolve views.
  • We created a controller and a view

Previous: Setup --- Up: Spring Fast Tutorial --- Next: Model View Controller

 

Feedback

Hi this is a gud tute. I did the example as given but Iam encountering an javax.servlet.ServletException:
Servlet.init() for servlet springmvc threw exception:
Root Cause: org.springframework.beans.factory.CannotLoadBeanClassException:
Cannot find class [springmvc.web.HelloWorldController] for bean with name '/hello_world.html' defined in ServletContext resource [/WEB-INF/springmvc-servlet.xml]; nested exception is java.lang.ClassNotFoundException: springmvc.web.HelloWorldController.
Can anyone help me out with this
Mitra
May 29, 2008
#1
Hi, I have done this hello world example as said here. But my output is only showing "This is my message: " It is not displaying the message from Controller. Can someone help me with this issue
Mitra
May 29, 2008
#2
Hi Mitra, Did you run the "ant" command before you started tomcat? That compiles the classes. The HelloWorldController class should be in <tomcat>/webapps/springmvc/WEB-INF/classes/springmvc/web folder. Suran WSO2, Inc.
Suran
June 25, 2008
#3
in eclipse IDE can we run above application with out use of build.xml (ant script)?
shrinivas
July 9, 2008
#4
if i want to run the above application in eclipse3.3 IDE what are the changes i have to do plz suggest. regards shrini
shrinivas
July 9, 2008
#5
even though i followed all the steps of configuration am getting these errors. can anybody solve this stuff. Error: Context initialization failed org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/springmvc-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/springmvc-servlet.xml] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:320) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:290)
shrini
July 16, 2008
#6
Its working. we can run above code in eclipse with out use of ant script.only we need to take care of folder structure of web application. :)
shrinivas
July 16, 2008
#7
syntax is not correct :<p>This is my message: ${message}</p> syntax correct is <p>This is my message:<c:out value="${message} "/></p>

July 28, 2008
#8
syntax is not correct :<p>This is my message: ${message}</p> syntax correct is <br> <p>This is my message:<c:out value="${message} "/></p>
igor
July 28, 2008
#9
Its not working for me... It gives me a 404... any help will be appreciated..
Paps
July 29, 2008
#10
Hi Paps. System.out.println("My log from HelloWorldController.handleRequest."); ******************************* Check the log console.U shoud see the message.The most likely u are missing some *.jar,
Igor
July 29, 2008
#11
Igor, this cumbersome <c:out/> syntax is useful only when you need XML escaping.
Jérôme Jaglale
July 29, 2008
#12
Hi Igor, Thanks for ur reply. My SOP's are not getting printed. I get the previous index.jsp page if i type "http://localhost/springmvc" but for "http://localhost/springmvc/hello_world.html" it gives 404. Nothing on tomcat console not even in log file of springmvc. I re-verified my jar's. I have allo em.. up2date.. wat cud be the problem??.. I m lil bit confused abt the springmvc-servlet.xml file.. I think thats the culprit.. Please go thro it an lemmi kno where i m wrong.. [code] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><!-- - Application context definition for "springapp" DispatcherServlet. --> <beans> <bean name = "/hello_world.html" class= "springmvc.web.HelloWorldController"> </bean> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/hello_world.html">hello_world</prop> </props> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>[/code]
Paps
July 30, 2008
#13
I resolved it.. there was some error in my springmvc-servlet.xml resolved it. this snippet was missing.. [code] <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> [/code] what i was having was.. [code] <beans> somecode... </beans> [/code] sorry Jérôme Jaglale for spoiling ur blog space :D.. hope u dont mind ;)...
Paps
July 30, 2008
#14
Hi Jérôme I used c:out in 1.st 1.This is my message1:Hello World MVC! and from posted tutorial I'm getting: 2.This is my message2:${message} do u have some idea what can be wrong in 2.nd case? anyway perfect tutorial Thanks Igor

July 30, 2008
#15
I tried but it doesn't work, i got the message:
javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:908) ...
when i accessed http://localhost:8080/springmvc/hello_world.html
What is the problem? I typed ant, to build the xml file from web-inf folder
Please help me
Thanks
Sorin
September 6, 2008
#16
Guys...the index page just has a "Hi" printed.It doesnt have any forward mapping or any kinda link to either of springmvc-servlet.xml or HelloWorldController.java.We do have index page in Struts application but they usually forward the control to other pages via the struts-config.xml...can anyone please cast some light on this doubt of mine!!
Soham
September 11, 2008
#17
@Soham Just use the below for index.jsp:

{{{
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:redirect url="/hello_world.html"/>
}}}
Nestor Urquiza
September 11, 2008
#18
thanx Nestor....that infact was the missing link..appreciated!!
soham
September 12, 2008
#19
ultimate.......... thnks 4 great efforts!!!
ariesrana
October 1, 2008
#20
It is a very good tutorial.. and most important thing is it works..
makarchus
October 12, 2008
#21
Please help. I follow this tutorial however I got HTTP Status 404 - type Status report message description The requested resource () is not available. Any ideas where is wrong? Thanks a lot
David
December 2, 2008
#22
It works without c:out. i.e. The code given in the tutorial is correct!! Thanks,
niranjan
February 2, 2009
#23
hi team. its wonderful site for spring. please give some more basic examples to know fully abut springs. thanks,
santhoshkumar
February 10, 2009
#24
hi, I got same result what David got. Even for source files provided in the Tutorial. Please help me.
Supun
April 1, 2009
#25
Hi I am encountring the same problem as mitra, javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception: Root Cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [springmvc.web.HelloWorldController] for bean with name '/hello_world.html' defined in ServletContext resource [/WEB-INF/springmvc-servlet.xml]; nested exception is java.lang.ClassNotFoundException: springmvc.web.HelloWorldController. Mitra how did you do it ? Can anyone help me out with this Thanks
rea
April 12, 2009
#26
Nice tuts!!!

May 11, 2009
#27
Thanks Alot
Ajeet
May 15, 2009
#28
The requested resource (?????? springmvc ????????) is not available.
zk
May 16, 2009
#29
Why this message is appear ? The requested resource (servlet springmvc cannot be used) is not available
ZK
May 16, 2009
#30
Very nice

May 22, 2009
#31
it's good example

May 27, 2009
#32
very nice
Dipak P
May 27, 2009
#33
Hi, I do not get error message, but ModelAndView object from controller does not pass to jsp. It does not print the message, when I execute the program. Please let me know where I am doing wrong. Thanks Jay
Jay
May 30, 2009
#34
Unless you copy the spring.jar, spring-webmvc.jar into WEB-INF/lib, you will get a message saying The requested resource (servlet springmvc cannot be used) is not available Cheers, Sandeep
Sandeep Shetty
June 3, 2009
#35
What can i say? it's just what i was looking for!!!, thanks guys, it was really helpful
John
June 7, 2009
#36
good
krissna
June 9, 2009
#37
Good one...good to start with
kasu
June 10, 2009
#38
Nice code to start up spring MVC but we need to mention redirect statement mentioned by Nestor Urquiza. Thanks guys
gayathri
June 15, 2009
#39
Hai all i have tried this example but giving the This is my message: ${firstName} please let me know the problem I a posting code here EmpFormController-servlet.xml [code] <?xml version="1.0" encoding="UTF-8" ?> <!-- ========================= VIEW DEFINITIONS ========================= --> <!-- ========================= DEFINITIONS OF PUBLIC CONTROLLERS ========================= --> [/code] Please helpme
Swaroop
July 8, 2009
#40
oh I am really very sorry I thought data is shown same on the forum page sorry here is the code <?xml version="1.0" encoding="UTF-8" ?>
Swaroop
July 8, 2009
#41
[code] <?xml version="1.0" encoding="UTF-8" ?> [/code]
swaroop
July 8, 2009
#42
Sorry I am not able to put my code in the blog,how can i display the in my jsp
swaroop
July 8, 2009
#43
[code][/code] not working do i need to do any chenages to my servlet.xml,if so where

July 8, 2009
#44
Great tutorial !
redhat
July 24, 2009
#45
Hi, I am getting this error: Jul 31, 2009 1:31:31 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound WARNING: No mapping found for HTTP request with URI [/springmvc/hello_world.html ] in DispatcherServlet with name 'springmvc' Anybody? Thanks
Ruchi
July 31, 2009
#46
Hi All, Generally all will face the same problem due to Ant build file so in build.properties file use this two lines,based on the tomcat folder you installed appserver.home=C:\Tomcat 5.5 appserver.lib=${appserver.home}/common/lib I think after doing this you may not find any problem like ClassNotFoundException
chandra
August 2, 2009
#47
Hi, I am getting this error org.springframework.web.servlet.DispatcherServlet noHandlerFound WARNING: No mapping found for HTTP request with URI [/springmvc/hello_world.html ] in DispatcherServlet with name 'springmvc' Anybody? Thanks
Dragon
August 4, 2009
#48
man ur probabliy callling the wrong link http://localhost:8180/springmvc/hello_world.html" " make sure no space at the end of the link
trio
August 4, 2009
#49
trio
August 4, 2009
#50
Hi, I am running this project through Netbeans 6.7 and have installed Spring Framework 2.5 and Spring Web MVC 2.5 and I loaded all the files into the project and have compiled the HelloWorldController.java file again. But it seems that when I run the project I get the following error: Caused by: java.lang.IllegalArgumentException: Servlet mapping specifies an unknown servlet name springmvc Can someone help me in this regard. I am running Tomcat from within Netbeans.
Manis
August 5, 2009
#51
Hi i tried to run this example but when i type the taglib it shows an error saying "cannot find taglib discriptor for http://java.sun.com/jstl/core. Please let me know how to fix this
Sonali
August 19, 2009
#52
Hi all i tried to run this app ... but end up with the follwoing error. i have used spring-1.1.2.jar. org.springframework.beans.factory.BeanDefinitionStoreException: Line 5 in XML document from ServletContext resource [/WEB-INF/springex-servlet.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". org.xml.sax.SAXParseException: Document root element "beans", must match DOCTYPE root "null". plz help me,
Venkatesh
August 21, 2009
#53
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <html> <body> no

This is my message: ${message}

but </body> </html>
Svitlana
August 24, 2009
#54
My ant build didn't work. BUILD FAILED C:\apache-tomcat-5.5.28\webapps\springmvc\WEB-INF\build.xml:2 -5.5.28\webapps\springmvc\WEB-INF\${appserver.lib} not found. What am I missing?
CT
September 11, 2009
#55
Hi gr8 tutorial, but it creates the confussion ant build, u have not given details about ant build, how to build the application. Vinod Hire
Vinod
October 5, 2009
#56
Hi I worked for 2 years on Spring MVC and Hibernate, Now a days working in different environment. Today I read this tutorial and it refreshes my memories.. Very good tutorial It's Beauty is it's Simplicity.. Nice job
Abu Turab Munir
October 8, 2009
#57
hellow, i have changed the build.properties file trying to run it on windows: appserver.home=c:\xampp\tomcat appserver.lib=${appserver.home}\lib ant doesn't works: C:\xampp\tomcat\webapps\springmvc\WEB-INF>ant Buildfile: build.xml build: [javac] Compiling 1 source file to C:\xampp\tomcat\webapps\springmvc\WEB-INF \classes BUILD FAILED C:\xampp\tomcat\webapps\springmvc\WEB-INF\build.xml:20: c:\xampp\tomcat\webapps\ springmvc\WEB-INF\xampp omcatlib not found. Total time: 0 seconds thanks
max
October 13, 2009
#58
ok, fixed it by changing \ with / thanks
max
October 13, 2009
#59
i get error : org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [springmvc.web.HelloWorldController] for bean with name 'hello_world.html' defined in ServletContext resource [/WEB-INF/springmvc-servlet.xml]; nested exception is java.lang.ClassNotFoundException: springmvc.web.HelloWorldController when using the windows version of build.properties
max
October 13, 2009
#60
...replay to 'HTTP Status 404' ______________________________ ...into file springmvc-servlet.xml you have to write right path, if you write that’s mean yours hello_world.jsp location onto server is webapps/projectname/jsp/hello_world.jsp ...into my case (I suppose into others too) I wrote because my *.jsp located into webapps/projectname/hello_world.jsp ...URL into both case of course is http://localhost/projectname/hello_world.html
virtualcook
October 18, 2009
#61
...replay to 'HTTP Status 404' ...into file springmvc-servlet.xml you have to write right path, if you write property name="prefix" value="/jsp/"/ that’s mean yours hello_world.jsp location onto server is webapps/projectname/jsp/hello_world.jsp ...into my case property name="prefix" value="//"/ (I suppose into others too) I wrote because my *.jsp located into webapps/projectname/hello_world.jsp ...URL into both case of course is http://localhost/projectname/hello_world.html

October 18, 2009
#62
worked for me after changing mapping to: thanks!
NOX
October 20, 2009
#63
worked for me after changing mapping to: < bean name="/springmvc/hello_world.html" class="springmvc.web.HelloWorldController" /> thanks!
NOX
October 20, 2009
#64
Hi Friends, iam new to spring,deploying one existing application in tomcat6.0. iam getting welcome file.but next if click the link, iam getting below error. link is like this:click here WARNING: No mapping for [/shop/jsp/MVC/shop/addNewProduct.form] in DispatcherServlet with name 'shop' my shop-servlet.xml file is like this reqhandler1 reqhandler2 reqhandler3 <!-- reqhandler4--> listDao Please help me. regards Srinivas
Srinivas
October 28, 2009
#65
good explation clearly given easy to understand
madhavan
October 29, 2009
#66
good explation clearly given easy to understand
madhavan
October 29, 2009
#67
Its very Nice to get basic idea
Sarvesh
October 30, 2009
#68
Hi Guys i am getting the following error when i am typing the http://localhost:8080/SpringLoginDemo/hello_world.htm in my IE. type Status report message /SpringLoginDemo/jsp/hello_world.jsp description The requested resource (/SpringLoginDemo/jsp/hello_world.jsp) is not available.
Tuna
November 6, 2009
#69
i WAS getting the error org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [springmvc.web.HelloWorldController]. I reloaded the Web App through the Tomcat manager. Seemed to clear things up. Hope that helps.
Ray
December 3, 2009
#70
Great tuts...........thanks
ashfaque
December 4, 2009
#71
goog tuts ...thanks
xcom-vegance
December 29, 2009
#72
Good illustration. Thanks
Rajan
January 9, 2010
#73
I was getting "This is my message: ${message}" instead of "This is my message: Hello World MVC!" that I expected. The fix was to apply 2 changes to hello_world.jsp: First, use the syntax that Igor mentioned earlier. Second, change the uri in the header of the file from "http://java.sun.com/jsp/jstl/core" to "http://java.sun.com/jstl/core" as suggested by Svitlana. Note, I used WebLogic 8.1 for this example, not Tomcat so I don't know if that necessitated these changes, but it now works.
Vadim
January 14, 2010
#74
Thanks Rajan for your answer. That did the trick !
Thanks Subadhra
January 20, 2010
#75
I am unable to get this example working with Apache HTTP Server 2.2. It seems like the controller cannot locate the jsp.
beachtowel
February 3, 2010
#76
hi this such very good springmvc tutorial, when i was reading other tutorial i didn't understand it completely But when i tried this tutorial i got everything thanks
keyur
February 5, 2010
#77
thanx greate job

February 9, 2010
#78
Thanks
Ravi
March 10, 2010
#79