Spring MVC hello world annotation example
This tutorial is using Spring 2.5.6, you may interest at this Spring 3 MVC hello world example.
In this tutorial, we show you how to create a Spring @MVC annotation-based hello world example.
Technologies used :
- Spring 2.5.6
- JDK 1.6
- Maven 3
- Eclipse 3.6
P.S This annotation-based example is converted from last Spring MVC hello world XML-based example.
1. Spring Dependency
Spring @MVC is bundled in the same spring-webmvc.jar. Declares following dependencies in your Maven pom.xml file.
<!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency> <!-- Spring MVC framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>2.5.6</version> </dependency>
2. Controller & Handler Mapping
Now, you can use @Controller and @RequestMapping to replace the XML configuration.
- Controller – The controller class is no longer need to extends base controller like AbstractController or SimpleFormController, just simply annotate the class with a @Controller annotation.
- Handler Mapping – No more declaration for the handler mapping like BeanNameUrlHandlerMapping, ControllerClassNameHandlerMapping or SimpleUrlHandlerMapping, all are replaced with a standard @RequestMapping annotation.
File : HelloWorldController.java
package com.mkyong.common.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/welcome") public class HelloWorldController{ @RequestMapping(method = RequestMethod.GET) public ModelAndView helloWorld(){ ModelAndView model = new ModelAndView("HelloWorldPage"); model.addObject("msg", "hello world"); return model; } }
If the @RequestMapping is applied at class level (can apply at method level with multi-actions controller), it required to put a RequestMethod to indicate which method to handle the mapping request.
In this case, if an URI pattern “/welcome” is requested, it will map to this HelloWorldController, and handle the request with helloWorld() method.
3. View Resolver
Sadly, you are still required to configure the view resolver.
<beans ...> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
4. View
A simple JSP for demonstration.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <body> <h1>Spring MVC Hello World Annotation Example</h1> <h2>${msg}</h2> </body> </html>
5. Components Auto Scanning
To make Spring @MVC annotation work, you have to enable Spring’s auto component scanning feature through the <context:component-scan> element.
<beans ... xmlns:context="http://www.springframework.org/schema/context ... http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.mkyong.common.controller" /> </beans>
You may interest at this Spring auto scanning components article.
Spring Configuration
See a complete Spring configuration file.
File : mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.mkyong.common.controller" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
6. web.xml
No exception, you are still required to configure the web.xml to enable the Spring MVC features.
File : web.xml
... <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> ...
7. Demo
URL : http://localhost:8080/SpringMVC/welcome.htm

If you compare this Spring MVC annotation-based hello world example with previous XML-based example, you can see that this annotation approach is more easier and flexible in wiring the controller class and URL handler mapping, because you do not need to declare the controller class explicitly or extends any particular class.
Download Source Code
References
- Controller Javadoc
- RequestMapping Javadoc
- Spring MVC hello world XML-based example
- Spring auto scanning components






All of your tutorials are very nice,
Why do you add spring configurations/annotations unit testing examples.
Tried doing this with the latest Spring release but it did not compile – somehow it appears that the Controller and RequestMapping/RequestMethod classes must have moved. Still trying to figure that out.
Changed the POM’s spring entries to [3.1.0,) to get the latest, the code compiles now – but maven still throws up on the other dependencies in the tutorial.
Fixed my maven issues, but still getting a 404 error when trying to point my browser to the local tomcat ‘welcome.htm’. Any ideas?
Never mind, she works :-) more maven issues, but overall a nice job with the tutorial!
Was anyone able to run this example successfully?
I’m getting 404 not found for this URL:
http://localhost:8080/SpringMVC/welcome.htm
Well tested, and it’s working fine, did you find any error at your console or log file?
I’m using eclipse and a tomcat plugin to run the app
how did you package the app ?
did you run it on a standalone tomcat ?
I’m using Maven, just “mav war:war” or build it, Maven will pack everything for deployment.
Simple and nice example.
Just 1 question. Could we still make use of
and
in annotation-based controller method?
why i am facing this issue ?
SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1387)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1233)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3877)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4429)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
bro, you didn’t include Spring jars, build the downloaded project with Maven, it will download the entire project dependencies.
Thanks Bro
can u help me to understand beans lifecycle in spring MVC ?
When beans declared for any controller will be created ?
what abt controller instance ?
what abt bean instance ?
Normally, beans declared in Spring Ioc either XML file or auto scanning mode, will be created during your we project start up phase.
For detail explanation, or you want to study deep inside the bean life cycle, refer to this Spring doc or this.
Thanks dude.
[...] web mvc controllers in spring 2.5Spring MVC form handling example – XML versionSpring MVC hello world annotation exampleSpring MVC MultiActionController annotation example [...]
[...] “HelloWorldPage.jsp” back to user. Spring MVC in annotation You may interest at this Spring MVC hello world annotation example.Download Source Code Download it – SpringMVC-Hello-World-Example-XML.zip (7KB)ReferenceSpring [...]
Hi Yong,
Thanks for the simplest example of Annotations.
Which one do you prefer,whether to use annotation based or make use of spring-view.xml
I’m an old developer, more prefer XML-based, because it’s more manageable.
I followed the same steps as given here but I am getting resource not found. Do I need to include the below:-
Looking for a reply.
What your resource is not found? Please build with Maven.
Awesome Tutorial……Thanks for such easy to understand tuttorial….
great great great !! thank you !
Executed the same code but getting error
noHandlerFound No mapping found for HTTP request with URI
This is good website for creating and understanding the Spring Annotation…i have created my first annotation based Application using the help of this website….
So thanks a lot for providing such a nice Guidance to the developer…
Welcome, thanks for the kind comment, we all learn thought sharing…
[...] Spring MVC hello world annotation example Spring MVC hello world annotation example [...]
thanks , it really helped me out
One word… Awesome.
I read through all of your posts!! well maybe 99% of it.
Keep it up Mykong,
Thanks.
Thanks for your encouraging reply.
Thanks a lot for this kind of example… very clear vision..
Thanks a ton…. this website has been most favorable for me to learn Struts and spring framework..
Please keep updating us by such good example.
[...] Spring MVC hello world annotation example A Annotation-based Spring MVC hello world example. [...]