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.



436 Comments

  • Apurva 2 October, 2013, 23:16

    Worked … Gr8 Example …Kipit up .

  • AlifiyaK 5 October, 2013, 12:27

    Good One.

  • raju 5 October, 2013, 23:12

    I have created a Spring project following all the steps in but when i run the application in
    browser it shows the following error. Will you please help me ?
    HTTP Status 404 – /Spring_5oct/index.jsp

    ——————————————————————————–

    type Status report

    message /Spring_5oct/index.jsp

    description The requested resource is not available.

    ——————————————————————————–

    Apache Tomcat/6.0.37

  • raju 5 October, 2013, 23:25

    5 Oct, 2013 10:54:31 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files (x86)\Java\jre1.7.0\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files (x86)/Java/jre1.7.0/bin/client;C:/Program Files (x86)/Java/jre1.7.0/bin;C:\oraclexe\app\oracle\product\10.2.0\server\bin;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\PC Connectivity Solution\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Sony\VAIO Startup Setting Tool;;C:\Program Files (x86)\Windows Live\Shared
    5 Oct, 2013 10:54:31 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:Spring_5oct’ did not find a matching property.
    5 Oct, 2013 10:54:32 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    5 Oct, 2013 10:54:32 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 1443 ms
    5 Oct, 2013 10:54:32 PM org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    5 Oct, 2013 10:54:32 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.37
    5 Oct, 2013 10:54:34 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring FrameworkServlet ‘spring’
    5 Oct, 2013 10:54:34 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    INFO: FrameworkServlet ‘spring’: initialization started
    5 Oct, 2013 10:54:34 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing WebApplicationContext for namespace ‘spring-servlet’: startup date [Sat Oct 05 22:54:34 IST 2013]; root of context hierarchy
    5 Oct, 2013 10:54:34 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-servlet.xml]
    5 Oct, 2013 10:54:35 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2b16b8: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,viewResolver]; root of factory hierarchy
    5 Oct, 2013 10:54:37 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    INFO: FrameworkServlet ‘spring’: initialization completed in 3043 ms
    5 Oct, 2013 10:54:37 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    5 Oct, 2013 10:54:37 PM org.apache.jk.common.ChannelSocket init
    INFO: JK: ajp13 listening on /0.0.0.0:8009
    5 Oct, 2013 10:54:37 PM org.apache.jk.server.JkMain start
    INFO: Jk running ID=0 time=0/92 config=null
    5 Oct, 2013 10:54:37 PM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 4955 ms

  • raju 5 October, 2013, 23:26

    I have attached the console output here,for your help…………..

  • raju 6 October, 2013, 0:37

    I have resolved myself,i have added a classpath of apache in my .classpath file.
    Thanks for your tutorial :)

  • Mahesh Sachdeva 6 October, 2013, 10:18

    very Good tutorial .
    Cleared my lots of doubt but still have a query ..

    In the web.xml file ,

    spring
    *.html

    Above code will transform all the *.html requested to dispatcher servlet but further if we click on
    any link from *.jsp page then how it will processed by dispatcher servlet .

  • NDTV 6 October, 2013, 12:16

    This example is not working.If you want to run the properly then u have to changed the entry in web.xml file.you just change the url pattern ‘/’ with sign then after your code is working fine.

  • Ruchi 10 October, 2013, 13:44

    I am getting below error while running this program.

    HTTP Status 404 –

    ——————————————————————————–

    type Status report

    message

    description The requested resource () is not available.

    ——————————————————————————–

    Apache Tomcat/7.0.5

    Please help me

  • poonam 11 October, 2013, 15:30

    Hi,
    i am a begginar to spring out of the many blogs and sites available to learn spring, i found urs very well organised and giving a step by step guidance, specially for this framework.
    Now, as i tried out this example in my machine, i am getting error in these import statements,
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;and on this annotation,
    so i am not able print the welcome msg
    i am using Helios. also i have added all necessary jar as mention by you above
    @RequestMapping(value=”/hello”,method=RequestMethod.GET)
    As per my understanding, i tthough a jar would be missing…i have included all those jars mentioned by you in your example.
    Thanks

  • S M Reddy 30 October, 2013, 13:22

    Please add following jar in web-inf/lib to avoid this exception
    SEVERE: Servlet /MavenWeb threw load() exception java.lang.ClassNotFoundException:

    jar—>org.springframework.context.support-3.0.5.RELEASE.jar

  • Mahesh 11 November, 2013, 15:31

    clean explanaton. thanks

  • Anurag Mishra 12 November, 2013, 17:32

    Your this program is not working
    Spring 3 MVC: Create Hello World Application In Spring 3.0 MVC

    The link is http://viralpatel.net/blogs/spring-3-mvc-create-hello-world-application-spring-3-mvc/

    When I click on Say Hello link than it is giving 404 Error and program stops and I am not able to found error my using debug also.

    • Prasanthi 21 November, 2013, 14:54

      Change hello.html to hello.jsp in index.jsp page. Then it’ll work.
      But I didn’t get the message in hello.jsp. If you find it explain me.
      Thanks.Q

  • Sudha 21 November, 2013, 15:37

    I am trying to run the above program in eclipse but it shows the following error .Please tell me the reason.

    java.lang.NoClassDefFoundError: org/springframework/beans/factory/Aware
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820)
    at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    at org.apache.catalina.core.StandardWrapper.servletSecurityAnnotationScan(StandardWrapper.java:1177)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:461)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:279)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.Aware
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
    … 45 more

  • Ley 22 November, 2013, 18:47

    Great post!. Thanks very much.

  • Mimi 23 November, 2013, 21:53

    I come cross the same problem. after running the app I can get to the index page, but after clicking on the link I get 404 error.
    solution;
    remove the app from the server.
    double click on the server and click on open configuration
    go to the classpath and add click on add Jars
    select class path from your projetc

  • Shaik Mahaboob 25 November, 2013, 16:12

    Simple Spring MVC project, Working successfully.

    Thanks a lot..

  • BaileyWhaley 27 November, 2013, 4:43

    Hi Guys,
    I was facing the same problem as many of you, i.e. getting the index page however getting 404 error when I click on the link. I tried checking many forums and finally got the answer and it worked for me.
    As mentioned, in the very first step, copy all the required jar files to the lib folder through eclipse. Do not copy them outside of eclipse. Also, there is no need to add them to the buildpath, since when we copy them to the lib folder, they show up the “Libraries” under “Java Resources”. Also, create a new project altogether when following these steps because I have found that eclipse, tomcat together make some associations with the project and hence reworking on the project doesn’t help
    Hope this helps!

    • aaa 7 February, 2014, 18:48

      Thanks a lot!!

    • Sarah 20 February, 2014, 19:16

      Thanks, it worked !

  • Shahul Hameed 1 December, 2013, 22:49

    Hi,

    Could you please advise on the below error. When i try to execute the downloaded package (while starting the server), iam getting an error alert saying that “Starting Tomcat v6.0 Server at localhost has encountered a problem.” and below is the error log.

    Could you please advise what needs to be done to avoid this issue. Thanks in advance

    I have the set below in environment Variables
    CATALINA_HOME = C:\Shahul\Software\apache-tomcat-6.0.37;
    CLASS_PATH = C:\Shahul\Software\apache-tomcat-6.0.37;
    JAVA_HOME = C:\Program Files\Java\jdk1.6.0;
    Path = %JDK_HOME%\bin
    JDK_HOME = C:\Program Files\Java\jdk1.6.0

    Error Log from Console
    ———————————
    Dec 1, 2013 12:09:21 PM org.apache.catalina.core.AprLifecycleListener init
    INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk1.6.0/bin/../jre/bin/client;C:/Program Files/Java/jdk1.6.0/bin/../jre/bin;C:/Program Files/Java/jdk1.6.0/bin/../jre/lib/i386;C:\Sun\share\lib;C:\Sun\share\bin;C:\Program Files\Java\jdk1.6.0\bin;C:\Sun\MessageQueue\lib;C:\Sun\MessageQueue\bin;C:\oracle\product\10.2.0\db_1\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\system32;C:\MaxProjectClient;C:\Shahul\Software\eclipse kepler\eclipse;
    Dec 1, 2013 12:09:22 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.jee.server:test1′ did not find a matching property.
    Dec 1, 2013 12:09:23 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Dec 1, 2013 12:09:23 PM org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 3135 ms
    Dec 1, 2013 12:09:23 PM org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    Dec 1, 2013 12:09:23 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.37
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Caused by: java.lang.NoClassDefFoundError: javax/servlet/http/HttpServlet
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:56)

    … 6 more

  • Rakesh M 3 December, 2013, 12:41

    Hi , i got this error while running the application.
    can any one help please.
    source code is

    package com.knot.Spring3mvc.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);
    	}
    }
    
    
    index.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    	<a href="hello.html">Say Hello</a>
    </body>
    </html>
    
    Dec 3, 2013 12:36:51 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring FrameworkServlet 'spring'
    Dec 3, 2013 12:36:51 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    INFO: FrameworkServlet 'spring': initialization started
    root of factory hierarchy
    Dec 3, 2013 12:36:51 PM org.springframework.web.servlet.FrameworkServlet initServletBean
    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]: Constructor threw exception; nested exception is javax.xml.transform.TransformerFactoryConfigurationError: Provider org.apache.xalan.processor.TransformerFactoryImpl not found
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:946)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:892)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:479)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
    	at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    	at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    	at java.lang.Thread.run(Unknown Source)
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]: Constructor threw exception; nested exception is javax.xml.transform.TransformerFactoryConfigurationError: Provider org.apache.xalan.processor.TransformerFactoryImpl not found
    	at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:141)
    	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:72)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:939)
    	... 38 more
    Caused by: javax.xml.transform.TransformerFactoryConfigurationError: Provider org.apache.xalan.processor.TransformerFactoryImpl not found
    	at javax.xml.transform.TransformerFactory.newInstance(Unknown Source)
    	at org.springframework.http.converter.xml.AbstractXmlHttpMessageConverter.(AbstractXmlHttpMessageConverter.java:47)
    	at org.springframework.http.converter.xml.SourceHttpMessageConverter.(SourceHttpMessageConverter.java:45)
    
    • Rakesh M 4 December, 2013, 17:59

      yes i got the answer,
      application need a additional jar file xalan.
      add it to the lib folder . thats it

  • spring man 6 December, 2013, 5:07

    very clear. Thank you.

  • ismail 12 December, 2013, 15:40

    Hi
    I gone through whole tutorial. When I run it on Tomcat, using link
    http://localhost:8080/Spring3MVC/hello.html

    I am getting following error;

    Dec 12, 2013 10:06:58 AM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-bio-8009"]
    Dec 12, 2013 10:06:58 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 1762 ms
    Dec 12, 2013 10:07:02 AM org.springframework.web.servlet.PageNotFound noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/Spring3MVC/hello.html] in DispatcherServlet with name ‘spring’

    Can someone help.

    thanks

    • sat 19 December, 2013, 5:58

      hi Ismail,
      Make the below changes and re-run the app…
      1. Rename the servlet name to xyz in web.xml
      2. Rename the spring-servlet.xml to xyz-servlet.xml

      • lucky 5 February, 2014, 12:37

        Can you please illustrate a bit ..i am also facing the same issue

  • Melica 18 December, 2013, 16:40

    This tutorial is very helpful and clear one on the internet .
    Thank you .

  • Slawek 20 December, 2013, 1:57

    Thanks, best spring tutorial :)

  • Prabhakar 23 December, 2013, 17:06

    Hi guys who got exception like HTTP Status 404 –Requested Resource is not available.
    Those peoples should change the “hello.htm” in Index.jsp. Then you will overcome that exception.

  • Fawad Khaliq 24 December, 2013, 15:07

    This tutorial is quite good and helpfull for the beginers, i would like to contribute a little more.. yes this example is not running, all those who are facing the porblem of error after clicking over the link should do only the following
    in the web.xml file replace this:

    <url-pattern>*.html</url-pattern>
    

    with this

    <url-pattern>/</url-pattern> 
    

    and every thing is done. cheers :)

    • prashansa kumari 23 January, 2014, 21:00

      Thanks,after doing this it’s working.It’s such a nice tutorial for biggner

    • Ivan 29 March, 2014, 20:20

      Thank you a lot, Fawad!
      Finally, it is working.

    • Harsh 3 April, 2014, 12:08

      Thanks i got same error but its working fine now after you show suggestion.

  • Fawad Khaliq 24 December, 2013, 15:15

    This tutorial is very good and helpful for the beginers, i would like to contribute a little more.. all those who are facing the porblem of error after clicking over the link should do the following only.
    Replace this

    <url-pattern>*.html</url-pattern> 

    with this

    <url-pattern>/</url-pattern> 

    in the web.xml file and every thing is done. cheers.

    • Alok 13 February, 2014, 0:07

      Hi Fawad,
      Thanks for your solution. Its working fine. But could you please explain me how it is working with
      ‘/ ‘ but not with “*.html.”.

      Thanks

  • azzum waqar 30 December, 2013, 5:41

    I CANT FIND THESE JAR FILES
    commons-logging-1.0.4.jar
    jstl-1.2.jar

    WHERE ARE THEY?

  • azzum waqar 30 December, 2013, 5:51

    how do i copy all the jars there plus i cant find
    commons-logging-1.0.4.jar
    jstl-1.2.jar

  • Devyani 7 January, 2014, 18:41

    Awesome Explanation :)

  • Rajib 10 January, 2014, 9:19

    Great Tutorial

    I followed same steps but i am getting “”Cannot be resolved to a type” errors for @Controller and @Request Mapping annotations.

    Stacktrace from console

    Jan 09, 2014 10:30:18 PM org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /Spring3MVC threw load() exception
    java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:142)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5176)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5460)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

    Can anyone please help?

  • Mahesh Kirdak 28 January, 2014, 10:02

    Thanks Sir.

  • Vel 31 January, 2014, 10:17

    Great Explanation. Could you please guide me on how to retrive data from any table that is cretaed in SQL server or Mysql using spring MVC.

  • Gustaph 18 February, 2014, 3:06

    HI

    <html>
    
    <head>
        <title>Spring 3.0 MVC Series: Hello World - ViralPatel.net</title>
    </head>
    <body>
        ${message}
    </body>
    </html>
    

    Did not do it for me before I used a taglib to output the message, like this

    <?xml version="1.0" encoding="UTF-8" ?>
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="com.geekcap.geeknews.core.*,java.util.List"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    	<title>Spring 3.0 MVC Series: Hello World - ViralPatel.net</title>
    </head>
    <body>	
    	<c:out value="${message}"/>
    </body>
    </html>
    
    
  • Nithesh 19 February, 2014, 17:41
    <html>
    <head>
        <title>Spring 3.0 MVC Series</title>
    </head>
    <body>
        
    <h1>Hello  Data is ${message}</h1>
    </body>
    </html>
    

    I am getting the result “Hello Data is ” but I am not able to print the value stored in the variable message

  • Ndy 3 March, 2014, 20:38

    For people experiencing the 404 error, ensure that index.jsp is under WebContent. In the tutorial, it is stated to create index.jsp as “WebContent/index.jsp,” however, it is intuitively easy to create it under “WebContent/WEB-INF/jsp” (just like hello.jsp) as it is a *.jsp file after all.

    Thanks to the author for this turoial :-)

  • saurabh 4 March, 2014, 14:02

    Hi , i am getting following error in web.xml( i did in same way you explain)

    Error 1
    file name references to “index.jsp” that does not exist in web content.(i have put file in correct folder)

    Error 2
    servlet-class references to
    “org.springframework.web.servlet.DispatcherServlet” that does not
    implement interface javax.servlet.Servlet

    Due to above 2 error i am not able to run.

  • Aditya 12 March, 2014, 18:54

    Hi Viral,

    Can you help me in generating rest services using spring with hibernate,

    Thanks in Advance

  • Simran 15 March, 2014, 23:34

    Nice explanation.. Regarding 404 Error.. Please create new Project donot import.. because tomcat will not able to recognize.. and in web.xml copy this

    spring
    /
    .. it will work..

  • Preethi G 19 March, 2014, 14:26

    Thank You Viral. The code really works.And the explanation is also very helpful.

  • Adarsh S 11 April, 2014, 13:40

    I am not able to see the ${message} value in 2 end (hello.jsp) page.Please let me know is there how i ll do it ?

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]