Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Spring Spring MVC Hello World Example

 
 

Share on Google+Share on Google+

Spring MVC Hello World Example

Advertisement
Develop Hello World example in Spring MVC.

Spring MVC Hello World Example

     

Spring MVC Hello World Example in Spring 2.5

In this tutorial we will develop the Spring MVC Example and then run on the Tomcat server.

We are using Spring 2.5 for this tutorial. We will also explain you the process of creating the dynamic web application in Eclipse IDE version 3.5.2. We will use tomcat to run the example. Eclipse provides the way to easily run the example from the IDE.

Step 1:

The initial step is to create Dynamic Web Project in eclipse. To create a new Dynamic project in Eclipse IDE select File -> Dynamic Web Project as shown below.

Spring MVC New Project

Step 2:

After that New Dynamic Project Window will appear on the screen and you will enter the web application name in the Project name text box. Enter Hello World in the Project Name and then click Next button.

Spring MVC New Project

We will enter the project name and set the project location and set the target runtime (Apache Tomcat server) just click on New button after that a New Server Runtime Environment window will appear, select the latest version of runtime environment and click Next button and Download and install the Tomcat Server and click on Finish button and also click on Finish button in Dynamic Web Project creation window.

Select Tomcat

Tomcat Server path

Step 3:

After that we will set the nature of the project just right click on the project and select Spring Tools with Add Spring Project Nature.

New Hello World Project

Step 4:

We will add all Spring Web MVC 2.5 jar files.

Adding Spring Libraries

After that Build Path window will appear on the IDE screen look like

Select Jar files

After that we will select the Libraries tab and click on Add External Jars button for add jar files. After selecting all Spring 2.5 Web MVC jar file we will click on Ok button and jar files is appears in your project lib folder.

Spring libraries in eclipse project

Now your project will created  in Eclipse IDE.

Step 5:

Now we will created a index.jsp in project's WebContent  folder. In the jsp file we will create a new hyperlink "Hello World !" that will be linked to hello.html page.  The code of index.jsp is:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

<body>

<a href="hello.html">Hello World</a>

</body>

</html>

Step 6:

Now we will configure the DispatcherServlet in web.xml file. The DispatcherServlet will be configured to process all the request ending with .html.

Here is the code of configuring DispatcherServlet in web.xml file:

<servlet>
  <servlet-name>dispatcher</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
 </servlet>
<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>*.html</url-pattern>
</servlet-mapping>

The full code of web.xml file is:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"

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_5.xsd" >

<servlet>

<servlet-name>dispatcher</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>dispatcher</servlet-name>

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

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

Step 7:

Now we will create a new xml file called dispatcher-servlet.xml in the WEB-INF folder of the web application. This is the main configuration file for the Spring MVC. Here we will define the ViewResolver, the code for defining the view resolver is as shown below:

<bean id="viewResolver"   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
  <value>/WEB-INF/jsp/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
</bean>

The view resolver looks for the jsp files in the /WEB-INF/jsp/ directory.

The we have to define bean for org.springframework.web.servlet.handler.SimpleUrlHandlerMapping  as shown below:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

Then we will define the url mapping with the Controller bean as shown below:

<map>
<entry key="/hello.html">
<ref bean="helloController"/>
</entry>
</map>

Finally we will define the Controller bean as shown below:

<bean id="helloController" class="net.roseindia.web.HelloWorldController"> </bean>

 

The full code of dispatcher-servlet.xml file is:

<?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"

xmlns:p="http://www.springframework.org/schema/p">

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<value>/WEB-INF/jsp/</value>

</property>

<property name="suffix">

<value>.jsp</value>

</property>

</bean>

<bean id="urlMapping"

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="interceptors">

<list>

<ref local="localeChangeInterceptor"/>

</list>

</property>

<property name="urlMap">

<map>

<entry key="/hello.html">

<ref bean="helloController"/>

</entry>

</map>

</property>

</bean>

<bean id="helloController" class="net.roseindia.web.HelloWorldController"> </bean>

<bean id="localeChangeInterceptor" class="
org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
>

<property name="paramName" value="hl"/>

</bean>

<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>

</beans>

Step 8:

After that we will creates the controller class in the project src folder. This will be used as the controller for the hello.html request. The code of the  HelloWorldController.java calss is:

package net.roseindia.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 responsethrows ServletException, IOException {
 
  String Mess = "Hello World!";
 
  ModelAndView modelAndView = new ModelAndView("hello");
  modelAndView.addObject("message", Mess);
 
  return modelAndView;
  }
}

After that we will create a hello.jsp in the WEB-INF folder by create a jsp folder. The WEB-INF/jsp/hello.jsp code is:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<body>

<c:out value="${message}"/>

</body>

</html>

Step 9:

To run the example select Run -> Run As -> Run On Server from the menu and then run the application on tomcat server. Eclipse will start Tomcat server and deploy the application on the Tomcat. Ellipse will also open the application in it internal browser as shown below:

Click on the "Hello World" link to test the application. It should display the "Hello World" message as shown below.

Download code:

Download this example code

You can download the code from the above url and then import the project in Eclipse IDE.

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 19, 2010

Related Tutorials

Discuss: Spring MVC Hello World Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:13
Deepti Arora
May 28, 2012
Problem in executing this example

I have imported the above code in eclipse.First page is loaded.When i click on the "Hello World" link, an error is displayed "HTTP Status 404 - Servlet dispatcher is not available". The console is as follows May 28, 2012 9:47:16 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\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;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)\Windows Live\Shared;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\OEM\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\OEM\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\OEM\12.0\DLLShared\;C:\Program Files (x86)\Roxio\OEM\AudioCore\;C:\Maven\apache-maven-3.0.4\bin;. May 28, 2012 9:47:16 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorld_old' did not find a matching property. May 28, 2012 9:47:16 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorld' did not find a matching property. May 28, 2012 9:47:16 PM org.apache.coyote.AbstractProtocolHandler init INFO: Initializing ProtocolHandler ["http-bio-8080"] May 28, 2012 9:47:16 PM org.apache.coyote.AbstractProtocolHandler init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] May 28, 2012 9:47:16 PM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 628 ms May 28, 2012 9:47:16 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina May 28, 2012 9:47:16 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.12 May 28, 2012 9:47:17 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(C:\Users\Deepti\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\HelloWorld\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class May 28, 2012 9:47:17 PM org.apache.catalina.core.ApplicationContext log INFO: Marking servlet dispatcher as unavailable May 28, 2012 9:47:17 PM org.apache.catalina.core.StandardContext loadOnStartup SEVERE: Servlet /HelloWorld threw load() exception java.lang.ClassNotFoundException: javax.servlet.ServletException at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1591) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521) at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Unknown Source) at java.lang.Class.getConstructor0(Unknown Source) at java.lang.Class.newInstance0(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:119) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1062) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1010) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4935) at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5262) at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5257) 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) May 28, 2012 9:47:17 PM org.apache.coyote.AbstractProtocolHandler start INFO: Starting ProtocolHandler ["http-bio-8080"] May 28, 2012 9:47:18 PM org.apache.coyote.AbstractProtocolHandler start INFO: Starting ProtocolHandler ["ajp-bio-8009"] May 28, 2012 9:47:18 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 1208 ms May 28, 2012 9:47:22 PM org.apache.catalina.core.StandardWrapperValve invoke INFO: Servlet dispatcher is currently unavailable Please tell me the way to resolve the problem
Jai
May 31, 2012
Error Info

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [spring.mvc.servlet.web.HelloWorldController] for bean with name 'helloController' defined in ServletContext resource getting this error . do not know why?? class file is at right place.
alen
June 8, 2012
cannot find spring elements

when i use right click to find "inspect element", i cant found it.. any solution for my problem. i use eclipse europa..
Mayuri
July 12, 2012
Spring

Hello i m new in this field want to know the basics. will u plz help me out?
stra(wh)anger
August 23, 2012
thnx

thank you for a working sample..
punit
September 5, 2012
nice

nice example..!! i run in one shot...
Nadeesha
November 8, 2012
Error JSTL

I have done exactly the above. But getting following error. Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core" I have added jstl.jar in my build path as well.
Mohankumar
April 16, 2013
Spring mvc

Thanks for tutorial
Deepti Arora
May 28, 2012
Problem in executing this exapmle

I have imported the above example in eclipse.When i run the example first page is loaded. When i click on "Hello World" link an error is displayed "HTTP Status 404 - Servlet dispatcher is not available". Please tell me the way to resolve the problem. The console is as follows:- May 28, 2012 9:47:16 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\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;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)\Windows Live\Shared;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\OEM\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\OEM\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\OEM\12.0\DLLShared\;C:\Program Files (x86)\Roxio\OEM\AudioCore\;C:\Maven\apache-maven-3.0.4\bin;. May 28, 2012 9:47:16 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorld_old' did not find a matching property. May 28, 2012 9:47:16 PM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HelloWorld' did not find a matching property. May 28, 2012 9:47:16 PM org.apache.coyote.AbstractProtocolHandler init INFO: Initializing ProtocolHandler ["http-bio-8080"] May 28, 2012 9:47:16 PM org.apache.coyote.AbstractProtocolHandler init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] May 28, 2012 9:47:16 PM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 628 ms May 28, 2012 9:47:16 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina May 28, 2012 9:47:16 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.12 May 28, 2012 9:47:17 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(C:\Users\Deepti\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\HelloWorld\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class May 28, 2012 9:47:17 PM org.apache.catalina.core.ApplicationContext log INFO: Marking servlet dispatcher as unavailable May 28, 2012 9:47:17 PM org.apache.catalina.core.StandardContext loadOnStartup SEVERE: Servlet /HelloWorld threw load() exception java.lang.ClassNotFoundException: javax.servlet.ServletException at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1591) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521) at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Unknown Source) at java.lang.Class.getConstructor0(Unknown Source) at java.lang.Class.newInstance0(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:119) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1062) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1010) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4935) at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5262) at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5257) 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) May 28, 2012 9:47:17 PM org.apache.coyote.AbstractProtocolHandler start INFO: Starting ProtocolHandler ["http-bio-8080"] May 28, 2012 9:47:18 PM org.apache.coyote.AbstractProtocolHandler start INFO: Starting ProtocolHandler ["ajp-bio-8009"] May 28, 2012 9:47:18 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 1208 ms May 28, 2012 9:47:22 PM org.apache.catalina.core.StandardWrapperValve invoke INFO: Servlet dispatcher is currently unavailable
DMCA.com