Spring MVC hello world annotation example

Note
This tutorial is based on Spring 2.5.6, quite outdated. Try considering the new tutorials :

  1. Gradle + Spring 4 MVC Hello World
  2. Maven + Spring 3 MVC Hello World

In this tutorial, we will take the previous Spring MVC hello world XML-based, and convert it to a annotation-based project.

Technologies used :

  1. Spring 2.5.6
  2. JDK 1.6
  3. Maven 3
  4. Eclipse 3.6

1. Directory Structure

spring2-mvc-annotation-hello-world

2. Maven

Spring’s annotation is bundled in the same spring-webmvc.jar.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
	http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.common</groupId>
	<artifactId>spring2-mvc-annotation-hello-world</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>Spring 2 MVC</name>
	
	<properties>
		<jdk.version>1.6</jdk.version>
		<spring.version>2.5.6</spring.version>
		<jstl.version>1.2</jstl.version>
		<servletapi.version>2.5</servletapi.version>
	</properties>
	
	<dependencies>

		<!-- Spring MVC framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- JSTL -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>${jstl.version}</version>
		</dependency>

		<!-- for compile only, your container should have this -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>${servletapi.version}</version>
			<scope>provided</scope>
		</dependency>
		
	</dependencies>

	<build>
		
	  <plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.3</version>
			<configuration>
				<source>${jdk.version}</source>
				<target>${jdk.version}</target>
			</configuration>
		</plugin>

		<plugin>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-maven-plugin</artifactId>
			<version>9.2.11.v20150529</version>
			<configuration>
				<scanIntervalSeconds>10</scanIntervalSeconds>
				<webApp>
					<contextPath>/spring2</contextPath>
				</webApp>
			</configuration>
		</plugin>

		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-eclipse-plugin</artifactId>
			<version>2.9</version>
			<configuration>
				<downloadSources>true</downloadSources>
				<downloadJavadocs>true</downloadJavadocs>
				<wtpversion>2.0</wtpversion>
				<wtpContextName>spring2</wtpContextName>
			</configuration>
		</plugin>
			
	  </plugins>
		
	</build>

</project>

3. Controller & Handler Mapping

Now, you can use @Controller and @RequestMapping to replace the XML configuration.

  1. Controller – The controller class is no longer need to extend the base controller like AbstractController or SimpleFormController, just simply annotate the class with a @Controller annotation.
  2. Handler Mapping – No more declaration for the handler mapping like BeanNameUrlHandlerMapping, ControllerClassNameHandlerMapping or SimpleUrlHandlerMapping, all are replaced with a standard @RequestMapping annotation.
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 the 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 a URI pattern /welcome is requested, it will map to this HelloWorldController, and handle the request with helloWorld() method.

4. Spring XML Configuration

You still need to configure the view resolver and component scanning in XML file.

/WEB-INF/spring-mvc-config.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">

	<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>
	
	<context:component-scan base-package="com.mkyong.common.controller" />

</beans>

5. JSP Page

A simple JSP page for demonstration.

HelloWorldPage.jsp.

<%@ 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>

6. web.xml

web.xml

<web-app id="WebApp_ID" 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">

	<display-name>Spring Web MVC Application</display-name>

	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring-mvc-config.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>

</web-app>

7. Demo

6.1 To run with the embedded Jetty, type :


$ mvn jetty:run

URL : http://localhost:8080/spring2/welcome.htm

spring2-mvc-annotation-demo

6.2 To import into Eclipse IDE.


$ mvn eclipse:eclipse
Note
If you compare this Spring MVC annotation-based hello world example with previously XML-based example, you can see that this annotation approach is 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

Download it – spring2-mvc-annotation.zip (15 KB)

References

  1. Controller Javadoc
  2. RequestMapping Javadoc
  3. Spring MVC hello world XML-based example
  4. Spring auto scanning components

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
mkyong
Guest
mkyong

Article is updated, new URL : http://localhost:8080/spring2/welcome.htm

This tutorial is based on Spring 2.5.6, quite outdated. Try considering the new tutorials :

1. Gradle + Spring 4 MVC Hello World
2. Maven + Spring 3 MVC Hello World

seenseke
Guest
seenseke

I have an error when I deploy the war in the server:

java.lang.ClassNotFoundExceptiorg.springframework.web.context.ContextLoaderListener server.

I check the Spring libraries generated with maven and everything is correct and if I unzip the war, the libraries there are:

C:UsersUsuario.m2repositoryorgspringframeworkspring-webmvc2.5.6spring-webmvc-2.5.6.jar

C:UsersUsuario.m2repositorycommons-loggingcommons-logging1.1.1commons-logging-1.1.1.jar

C:UsersUsuario.m2repositoryorgspringframeworkspring-beans2.5.6spring-beans-2.5.6.jar

C:UsersUsuario.m2repositoryorgspringframeworkspring-web2.5.6spring-web-2.5.6.jar

C:UsersUsuario.m2repositoryorgspringframeworkspring-core2.5.6spring-core-2.5.6.jar

C:UsersUsuario.m2repositoryorgspringframeworkspring-context2.5.6spring-context-2.5.6.jar

C:UsersUsuario.m2repositoryaopallianceaopalliance1.0aopalliance-1.0.jar

C:UsersUsuario.m2repositoryorgspringframeworkspring-context-support2.5.6spring-context-support-2.5.6.jar

C:UsersUsuario.m2repositoryjavaxservletjstl1.1.2jstl-1.1.2.jar

C:UsersUsuario.m2repositorytaglibsstandard1.1.2standard-1.1.2.jar

C:UsersUsuario.m2repositoryjavaxservletservlet-api2.5servlet-api-2.5.jar

why am I facing this issue ?

Johaness
Guest
Johaness

what the hell did you mix the xml with anotations what hell is it

maneesh
Guest
maneesh

can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core”

this error is coming in jsp file can you please help, thanks in advance

Raju
Guest
Raju

Hi really it is very useful….

Raju
Guest
Raju

Extremely thanks a lot for this kind of examples….

Please provide spring MVC videos Mkyong…..We can practice and at same time watch the video

Suyog
Guest
Suyog

Hi.
MKYONG,
I am developing above application in NetBeans with out Maven
so here I am getting following Error plz help me on this.
The prefix “context” for element “context:component-scan” is not bound
For this example spring 2.5 I am using

Java Lover
Guest
Java Lover

I am getting the below error.

WARNING: No mapping found for HTTP request with URI [/SpringMVC/] in DispatcherServlet with name ‘mvc-dispatcher’

Am I missing something.

Thuy
Guest
Thuy

Hi,
I found the correct request http://localhost:8080/welcome.htm

Java Lover
Guest
Java Lover

Hi
,
I am getting the below error.

WARNING: No mapping found for HTTP request with URI [/SpringMVC/] in DispatcherServlet with name ‘mvc-dispatcher’

Am I missing something.

mkyong
Guest
mkyong
Amol
Guest
Amol

Thanks mkyong…

Works like a charm for me :) :)

help
Guest
help

I’m getting this error when i tried to go on my “welcome” page :

Avertissement: StandardWrapperValve[dispatcher]: PWC1406: Servlet.service() for servlet dispatcher threw exception
java.lang.NullPointerException
...

Could you help me finding an issue ?

Satish
Guest
Satish

This is a very good website to learn new concepts very easily with the simple examples and clear explanation. Thanks a lot. Keep up the good work.

Andrey Kapelchik
Guest
Andrey Kapelchik

Are you sure that you will have no trouble finding paths in this example? The full path to your controller will be

main.java.com.mkyong.common.controller

when using the Maven. And you specify only

<context:component-scan base-package="com.mkyong.common.controller" />

in your mvc-dispatcher-servlet.xml.

Asghar Khan
Guest
Asghar Khan

This tells to the DispatcherServlet you have to search the controller in this package .

Devikumar R
Guest
Devikumar R
Am getting the below exception. Could you please help me out? 15:46:49,892 INFO [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/util]] (MSC service thread 1-3) Initializing Spring root WebApplicationContext 15:46:49,908 ERROR [org.springframework.web.context.ContextLoader] (MSC service thread 1-3) Context initialization failed: org.springframework.beans.factory.BeanDefinitionStoreException: I/O failure during classpath scanning; nested exception is java.io.IOException: No context factory for vfs:/C:/Dev/jboss-as-7.1.0.Final/bin/content/Util-0.0.1-SNAPSHOT.war/WEB-INF/classes/com/clink/controller/ at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:272) [spring-context-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242) [spring-context-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84) [spring-context-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1419) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1409) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:184) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.doRegisterBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:140) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:111) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:493) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:390) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) [spring-beans-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) [spring-web-3.1.0.RELEASE.jar:3.1.0.RELEASE] at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)… Read more »
Dan
Guest
Dan

You got a special trick to explain complex things in simple way.. I am not only meaning this post but all of them

hazarath
Guest
hazarath

hi,
how to get spring configurations(xml files) files, where you get those files.

giri
Guest
giri

sir,
pls tell how to change Projectname from “SpringMVC” to “MyProjectName”

Ram
Guest
Ram

All of your tutorials are very nice,
Why do you add spring configurations/annotations unit testing examples.

C
Guest
C

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.

C
Guest
C

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.

C
Guest
C

Fixed my maven issues, but still getting a 404 error when trying to point my browser to the local tomcat ‘welcome.htm’. Any ideas?

C
Guest
C

Never mind, she works :-) more maven issues, but overall a nice job with the tutorial!

Ari
Guest
Ari

Was anyone able to run this example successfully?
I’m getting 404 not found for this URL:
http://localhost:8080/SpringMVC/welcome.htm

Thuy
Guest
Thuy

Hi mkyong,
I still get 404 error although I try a lot and search Google a lot. It don’t run Controller, it seem that mvc-dispatcher does not work. There is nothing error in console log. Could you please recheck your coding. or you can give me file war instead?
Do you give me some hint for fix

Ethan Lew
Guest
Ethan Lew

Simple and nice example.

Just 1 question. Could we still make use of

HttpServletRequest

and

HttpServletResponse

in annotation-based controller method?

varun jain
Guest
varun jain

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)

trackback
Spring MVC form handling annotation example

[…] web mvc controllers in spring 2.5Spring MVC form handling example – XML versionSpring MVC hello world annotation exampleSpring MVC MultiActionController annotation example […]

trackback
Spring MVC hello world 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 […]

sikinder
Guest
sikinder

Hi Yong,
Thanks for the simplest example of Annotations.

Jayaprakash
Guest
Jayaprakash

Which one do you prefer,whether to use annotation based or make use of spring-view.xml

anu
Guest
anu

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.

Pritam Ghosh
Guest
Pritam Ghosh

Awesome Tutorial……Thanks for such easy to understand tuttorial….

bogdan_ro
Guest
bogdan_ro

great great great !! thank you !

Student
Guest
Student

Executed the same code but getting error
noHandlerFound No mapping found for HTTP request with URI

Harshal Patel
Guest
Harshal Patel

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…