Spring 3 MVC hello world example

Before you start this Spring 3 MVC tutorial, please refer to this new features in Spring 3 documentation, so that you have a brief idea of what’s new in Spring 3.

In this tutorial, we show you how to develop a Spring 3 MVC hello world example.

Technologies used :

  1. Spring 3.0.5.RELEASE
  2. JDK 1.6
  3. Maven 3
  4. Eclipse 3.6

1. Project Dependency

In Spring 3 @MVC, declares following dependencies in your Maven pom.xml file.

	<properties>
		<spring.version>3.0.5.RELEASE</spring.version>
	</properties>
 
	<dependencies>
 
		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
 
	</dependencies>
 
</project>

2. Controller & Mapping

In Spring 3, annotation is widely adapted in everywhere. The @RequestMapping is available since 2.5, but now enhanced to support REST style URLs in Spring MVC.

package com.mkyong.common.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
@RequestMapping("/welcome")
public class HelloController {
 
	@RequestMapping(method = RequestMethod.GET)
	public String printWelcome(ModelMap model) {
 
		model.addAttribute("message", "Spring 3 MVC Hello World");
		return "hello";
 
	}
 
}

3. JSP Views

A JSP page to display the value.

File : hello.jsp

<html>
<body>
	<h1>Message : ${message}</h1>	
</body>
</html>

4. Spring Configuration

In Spring 3, you still need to enable “auto component scanning” (for controller) and declares “view resolver” manually.

File : mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	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-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="com.mkyong.common.controller" />
 
	<bean
		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>

5. Integrate Web application with Spring

Integration is no different if compare with old Spring 2.5.6, just declares Spring “ContextLoaderListener” and “DispatcherServlet“.

File : 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 MVC Application</display-name>
 
	<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>/</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>
 
</web-app>

6. Demo

URL : http://localhost:8080/SpringMVC/welcome

spring 3 mvc demo

Download Source Code

Download it – Spring3-MVC-HelloWorld-Example.zip (7 KB)

References

  1. Spring 3 hello world example
  2. What new in Spring 3
  3. Spring 3 MVC and JSR303 @Valid example
  4. Spring 3 MVC and RSS feed example
  5. Spring 3 MVC and XML example
  6. Spring 3 MVC and JSON example
  7. Spring 3 REST hello world example
  8. Spring 2.5.6 MVC hello world example
  9. Spring 2.5.6 MVC hello world annotation example
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: parking()

  • Pingback: water ionizer()

  • Pingback: water ionizer machine()

  • Pingback: penge laan nu()

  • Pingback: car parking()

  • Pingback: fue()

  • Pingback: DIRECTV vs Cable()

  • Pingback: Click Here()

  • Pingback: streaming movies()

  • Pingback: how to loose weight()

  • Pingback: Blue Coaster33()

  • Mukesh Kumar Saini

    Hi mkyong,
    I follow your tutorial to demo a spring mvc.while running this i am getting “HTTP status 404 requested resource is not avaiable” error. plz help me to sort out this

    • Mukesh Kumar Saini

      Hi,
      I found the solution and now it’s working.Thanks for this tutorial

  • Phuc

    Thanks for your tutorial, it very helpful for me.
    I make a mistake when did this tutorial, when i run on server, the default page is localhost:8080/Spring3MVC1/, and it show the value of index.jsp (“Hello world”), when i change address to “http://localhost:8080/Spring3MVC1/welcome”, the 404 error, can you help me :(

  • Shiva

    I am getting below error while running on server. Please let me know if I am missing anything.

    ——————————————————-
    Throwable occurred: java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    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.StandardContext.listenerStart(StandardContext.java:4149)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
    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:45)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:599)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

    • Shiva

      Resolved this issue following this thread.

      http://www.mkyong.com/spring/spring-error-classnotfoundexception-org-springframework-web-context-contextloaderlistener/

      Following this fix, I encountered with below error.

      Caused by: java.lang.ClassNotFoundException: org.springframework.web.bind.annotation.RequestMapping

      Please throw some light on this issue.

      • Shiva

        Below the trace for more information.

        —————————————-

        Throwable occurred: java.lang.TypeNotPresentException: Type org.springframework.web.bind.annotation.RequestMapping not present
        at com.ibm.oti.reflect.AnnotationHelper.getAnnotation(AnnotationHelper.java:38)
        at com.ibm.oti.reflect.AnnotationHelper.getDeclaredAnnotations(AnnotationHelper.java:50)
        at com.ibm.oti.reflect.Method.getDeclaredAnnotations(Method.java:31)
        at java.lang.reflect.Method.getDeclaredAnnotations(Method.java:687)
        at java.lang.reflect.AccessibleObject.getAnnotations(AccessibleObject.java:186)
        at com.ibm.oti.reflect.Method.getAnnotation(Method.java:19)
        at java.lang.reflect.Method.getAnnotation(Method.java:677)
        at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$1.doWith(InitDestroyAnnotationBeanPostProcessor.java:205)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:466)
        at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:443)
        at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.buildLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:202)
        at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.findLifecycleMetadata(InitDestroyAnnotationBeanPostProcessor.java:190)
        at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(InitDestroyAnnotationBeanPostProcessor.java:119)
        at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessMergedBeanDefinition(CommonAnnotationBeanPostProcessor.java:275)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors(AbstractAutowireCapableBeanFactory.java:745)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:448)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
        at java.security.AccessController.doPrivileged(AccessController.java:224)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
        at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
        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:45)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
        at java.lang.reflect.Method.invoke(Method.java:599)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
        Caused by: java.lang.ClassNotFoundException: org.springframework.web.bind.annotation.RequestMapping
        at java.lang.Class.forName(Class.java:169)
        at com.ibm.oti.reflect.AnnotationHelper.getAnnotation(AnnotationHelper.java:33)
        … 44 more

  • Pingback: Spring MVC can’t reach application on Tomcat | Technology & Programming Answers()

  • James

    Sofar the best Tutorial I could found.

    Thank you for sharing

  • Khalil

    Excellent example for the beginner –
    Pls note the url should be http://localhost:8080/SpringMVC/welcome.htm

    • http://[email protected] Tien

      It doesn’t work :
      http://localhost:8080/SpringMVC/welcome
      http://localhost:8080/SpringMVC/welcome.htm

      HTTP Status 404 –

      type Status report

      message

      description The requested resource is not available.