Spring MVC Hello World

15/07/2012

Spring is the most popular open source java application framework as of current moment. It is one of the best job enablers too (at least in Indian software services companies).

Before starting on spring framework, I recommend you to become strong in core-java first, then remember to study servlets, jsp and then start on Spring framework.

Spring framework provides multiple modules wherein MVC and Inversion of Control container are popular among them. In this article I will present a spring MVC based Hello World web application.

I am using Spring version 3 latest available now. SpringSource provides a tool suite (STS) IDE which is based on Eclipse to develop Spring based applications. But, my personal choice for now is to continue with Eclipse JEE IDE.

Model View Controller (MVC)

Model view controller is a software architecture design pattern. It provides solution to layer an application by separating three concerns business, presentation and control flow. Model contains business logic, controller takes care of the interaction between view and model. Controller gets input from view and coverts it in preferable format for the model and passes to it. Then gets the response and forwards to view. View contains the presentation part of the application.

Spring MVC

Spring MVC is a module for enabling us to implement the MVC pattern. Following image shows the Spring’s MVC architecture

DispatcherServlet

This class is a front controller that acts as central dispatcher for HTTP web requests. Based on the handler mappings we provide in spring configuration, it routes control from view to other controllers and gets processed result back and routes it back to view.

Control Flow in Spring MVC

  1. Based on servletmapping from web.xml request gets routed by servlet container to a front controller (DispatcherServlet).
  2. DispatcherServlet uses handler mapping and forwards the request to matching controller.
  3. Controller processes the request and returns ModeAndView back to front controller (DispatcherServlet). Generally controller uses a Service to perform the rules.
  4. DispatcherServlet uses the view resolver and sends the model to view.
  5. Response is constructed and control sent back to DispatcherServlet.
  6. DispatcherServlet returns the response.

Spring 3 MVC Sample

Software versions used to run the sample code:

  • Spring 3
  • Java 1.6
  • Tomcat 7
  • JSTL 1.2
  • Eclipse Java EE IDE

Web Application Structure

Use Java EE perspective and create a new dynamic web project. Let us start with web.xml

web.xml

In web.xml primarily we are doing servlet mapping to give configuration for DispatcherServlet to load-on-startup and defining spring configuration path.

<?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>Spring Hello World</display-name>
    <welcome-file-list>
        <welcome-file>/</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>springDispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/spring-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springDispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Spring Configuration

This spring configuration file provides context information to spring container. In our case,

The tag mvc:annotation-driven says that we are using annotation based configurations. context:component-scan says that the annotated components like Controller, Service are to be scanned automatically by Spring container starting from the given package.

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        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.javapapers.spring.mvc" />
	<mvc:annotation-driven />

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

</beans>

Library files needed

  • commons-logging.jar
  • org.springframework.asm-3.1.2.RELEASE.jar
  • org.springframework.beans-3.1.2.RELEASE.jar
  • org.springframework.context-3.1.2.RELEASE.jar
  • org.springframework.core-3.1.2.RELEASE.jar
  • org.springframework.expression-3.1.2.RELEASE.jar
  • org.springframework.web.servlet-3.1.2.RELEASE.jar
  • org.springframework.web-3.1.2.RELEASE.jar
  • javax.servlet.jsp.jstl-1.2.1.jar (http://jstl.java.net/download.html -> JSTL Implementation)

These jars are part of standard spring framework download except the jstl.

Controller

Following controller class has got methods. First one hello maps to the url ‘/’. Annotation has made our job easier by just declaring the annotation we order Spring container to invoke this method whenever this url is called. return “hello” means this is used for selecting the view. In spring configuration we have declared InternalResourceViewResolver and have given a prefix and suffix. Based on this, the prefix and suffix is added to the returned word “hello” thus making it as “/WEB-INF/view/hello.jsp”. So on invoking of “/” the control gets forwarded to the hello.jsp. In hello.jsp we just print “Hello World”.

org.springframework.web.servlet.view.InternalResourceViewResolver

Added to printing Hello World I wanted to give you a small bonus with this sample. Just get an input from user and send a response back based on it. The second method “hi” serves that purpose in controller. It gets the user input and concatenates “Hi” to it and sets the value in model object. ‘model’ is a special hashmap passed by spring container while invoking this method. When we set a key-value pair, it becomes available in the view. We can use the key to get the value and display it in the view which is our hi.jsp. As explained above InternalResourceViewResolver is used to resole the view.

package com.javapapers.spring.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

	@RequestMapping("/")
	public String hello() {
		return "hello";
	}

	@RequestMapping(value = "/hi", method = RequestMethod.GET)
	public String hi(@RequestParam("name") String name, Model model) {
		String message = "Hi " + name + "!";
		model.addAttribute("message", message);
		return "hi";
	}

}

View – Hello World

<html>
<head>
<title>Home</title>
</head>
<body>
	<h1>Hello World!</h1>

<hr/>

	<form action="hi">
		Name: <input type="text" name="name"> <input type="submit" value="Submit">
	</form>

</body>
</html>

Use key “message” in model to get the value and print it.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
    <head>
        <title>Result</title>
    </head>
    <body>
        <h1><c:out value="${message}"></c:out></h1>
    </body>
</html>

Hello World Output


Download SpringMVC Sample Code and Run it!

Voila! I have started on Spring!

Ads by Google

95 comments on “Spring MVC Hello World

  1. Hi Joe…

    Thank.
    Simple and great document.

  2. @Suman

    Its really nice.
    It will really helps to the beginners and thanks for your efforts.

  3. You are one of the best teachers. Very few genuinely share their knowledge. Greatly appreciate your work.. A sincere Thank you from Samy..

  4. Great. You started on Spring too :) Keep going.

  5. Very Nice.. It will be good to provide the simple example for each types of controllers in spring…

  6. hey joy.. you always writes awesome post.. i really love to read them.

    But why you jumped directly on Spring MVC. you should first start Spring Basics, DI, AOP and other topics.

    I wish you will do it soon. I am really eagar to read those topics on Javapapers.com as i know you will again write something good on those topics.

  7. Hello Joe,

    Nice to learn Spring framework from your blog, it is easy and more understandable.
    Thank you so much Joe and one more thing you told to learn servlet and jsp before starting Spring MVC, Can you please tell me what are the concepts should be known in Servlet and jsp.

  8. Hey Joe….It really help me a lot to understand the flow…and you explain it in very simply way….I have one doubt on Spring Tiles…So if it is possible then can you post the tutorial of Spring Tiles with your explanation(that is your touch)….

    Thanks a lot

  9. Hey Joe….It really help me a lot to understand the flow…and you explain it in very simply way….

    Your way to carter things are very illustrative.

  10. Ads by Google
  11. Thanks Joe!!

    I like and follow all your posts…

    Keep posting… :)

  12. Hi Joe!

    Thanks for initiating with Spring framework, really a useful article to head-start with Spring MVC.

    It would be great if you help us with the Spring Expression Language instead of JSTL.


    Sandeep

  13. Thanks for nice article..! Keep going..:)

  14. spring can be annotation based and xml based.

  15. Was actually hoping you would write on this exact same topic. I looked around on the internet. I couldn’t find anything so simply explained.
    Thanks a lot. U r my hero.

  16. very nice explanation and example.

    thanks.

  17. Hi Joe,

    it was a nice article. but i am somewhat confused about the Model. as you in first section you said that it contain business logic and afterwards you said that it will have data to used on the view layer.

    which is corret.

    Thanks you are doing very good job. :)

    - Mayur Kumar

  18. Very good explanation ,It is best for beginners..Thanks alot

  19. Its a awesome article I must say.Thank you very much.But would you please share more on Spring framework. Specially, please include IOC. Please please please. It will be very helpful to us. Thak you again.

  20. Hi Joe,
    I am trying to run the application but still facing some issues.
    I don’t see any errors in tomcat logs, server start up perfectely but still webpage is saying that Resoruce is not available.

    Please help me where i might be going wrong.

    Thanks
    Shailesh

  21. Hi Joe!

    I am working in spring application but I dont have this much of understanding regarding controller. Now i got it. Thanks!!!

  22. Hi Joe!
    If we are familiar with struts framework can we work on springs or anything else to be known in advance.

    Is there any similarities between struts and spring frameworks

  23. IAM GETTING THE FOLLOWING EXCEPTION…

    exception

    javax.servlet.ServletException: Servlet.init() for servlet springDispatcher threw exception
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    java.lang.Thread.run(Unknown Source)

    root cause

    java.lang.IllegalArgumentException: Method must not be null
    org.springframework.util.Assert.notNull(Assert.java:112)
    org.springframework.core.BridgeMethodResolver.findBridgedMethod(BridgeMethodResolver.java:65)
    org.springframework.beans.GenericTypeAwarePropertyDescriptor.(GenericTypeAwarePropertyDescriptor.java:67)
    org.springframework.beans.CachedIntrospectionResults.(CachedIntrospectionResults.java:251)
    org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:145)
    org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:296)
    org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1003)
    org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:857)
    org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
    org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:62)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:119)
    javax.servlet.GenericServlet.init(GenericServlet.java:212)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    java.lang.Thread.run(Unknown Source)

    PLEASE HELP ME..

    • Hi I am getting the same error please let me know what was the solution

  24. Hi Joe,
    The issue has been resolved now .

    Thanks
    Shailesh

    • How did you resolve the problem.Please help me.

  25. Pingback: How to find the java compiler target version from a java class file?

  26. Hi Jeo,

    Thank u so much for starting Springs MVC, as i am very interested to learn Springs, please provide a full flow and project Hierarchic so that we(Readers) can develop a simple application on springs MVC through your blog.

  27. Hi Jeo….

    Thank you so much to introduce about Spring MVC please also some libraries link to download it…….

  28. Pingback: Dependency Injection (DI) with Spring

  29. Thanks for sharing the valuable knowledge with us on spring. It is easy to understand for a beginner.

  30. Hi Jho,
    This is nice topic.
    Dillip Kumar

  31. Pingback: Spring ApplicationContext

  32. Hi Joe!
    Thank You for sharing your knowledge, please provide some articles on JSF.

  33. Awesome tutorial on MVC, you can find the basics tutorials of spring except MVC in java4s.com

  34. Getting this error, when i tried to run the program:

    org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/SpringMVC/] in DispatcherServlet with name ‘springDispatcher’

    I am new to Spring MVC, please help me out

    • There is no mapping controller method for the url springDispatcher.htm

  35. Pingback: Spring Annotation Based Controllers

  36. Hi, I am looking for good and simple example to learn spring, Here is the answer….
    Nice post.

  37. Any one can give link of org.springframework.asm-3.1.2.RELEASE.jar

  38. hi joe, i am your regular follower.i have just started to learn spring framework.and i m facing many difficulties.please post some tutorials about spring framework for begginer like me.It would be very helpful for us.

  39. hi,
    Your way of explanation is very helpful for
    freshers.your pasion is great. thanks a lot……….

    krishna chaitanya

  40. dear sir, am a regular follower of ur articles and it helps me a lot. Now, I want to learn spring framework and ur this article only my start up. Thanks a lot! Kindly suggest me some good books (or web references) to dig more about spring just as a beginner pls..

  41. Hi Joe,

    Your articles are wonderful. Looking for articles on Hibernate , Spring , EJB from you soon.

    Keep up the good work :)

  42. HI Joe,
    In my jsp there are 15 fields are there,
    in this case how capture these fields in servered. like

    @RequestMapping(value = “/login”, method = RequestMethod.GET)
    public String login(@RequestParam(“name”) String name, ModelMap model) {

    model.addAttribute(“message”, “Spring 3 MVC Hello World” + runtimeService.toString());
    return “login”;

    }

    But i don’t want to use @RequestParam(“name”). Is there any other option to bind as bean Object. like Login object.

    hope you got what i’am excepting.

    thxs in advanced.

  43. Hi joe i want a spring jdbc web application that is to insert some bulk records into mysql database can u explain me the example

  44. Hi Joe
    i am getting this………………How can i solve?org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/mvc]
    Offending resource: ServletContext resource [/WEB-INF/config/spring-context.xml]

    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
    at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
    at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
    at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:284)
    at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1317)
    at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1310)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.parseBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:135)
    at org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.registerBeanDefinitions(DefaultBeanDefinitionDocumentReader.java:92)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.registerBeanDefinitions(XmlBeanDefinitionReader.java:475)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:372)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:316)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:284)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:126)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:419)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:349)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:427)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:341)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1173)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:809)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)

  45. good job joy…thank so much for giving this example…its really helpfull for a beginer

  46. thanks a lot for your great tuto

    Are there a way to use it with maven?
    Do you have a recomandation to configure a pom.xml

  47. Unfortunately, i tested to makes it work but i’ve this error:
    org.springframework.web.servlet.DispatcherServlet noHandlerFound
    WARNING: No mapping found for HTTP request with URI [/helloWorldSpring/hi] in DispatcherServlet with name ‘springDispatcher’

  48. if any one have spring web service pls send the whole code

  49. thanks joe,
    thanks for giving this helpful example…

  50. hi i am shivani and i m very confused in return type in handler methods plz describe each return type with its use abd example,,,

  51. I only know about the names of return type and before the method name we have to mention it,besides this i don’t know anything that how exactly a controller decides to choose one type from all of them.
    Return type:::
    1.ModelAndView
    2.String
    3.View

    4.A Model object
    return new Products(1245);

    5.void

    6.A specific string:
    “redirect:/products”
    “forward:/products”

  52. Nice tutorial. Can you Please give some tutorial on java’s role in cloud technologies.

  53. Hi Joe,

    Its Easy to learn Spring framework from your blog,its good for beginners,and pls provide more examples in spring (in every sites they are providing only Hello World example ).So can u please provide some complex exp it will be more useful for beginners to work in it and understand deeply about spring.
    Thanks
    Midhun
    Mail Id:mids1989@gmail.com

  54. Hi Joe

    Thanks for this tutorial. it’s really helps me a lot.

  55. hi
    i am new to spring mvc
    in my project i need to display a child (jsp) from parent(jsp) with a dynamic list of data
    can you please help in this

    Thanks for this tutorial

  56. Hi Joe

    Your site is really superb .

    The first thing i open in my system is javapapers.com.

    thanks joe.

    I would like to know how spring mvc is more better than struts2.I know abt structs 2 but very little abt spring

  57. Hello Sir,
    I tried to run given demo application (SpringMVC) from browser (http://localhost:8080/SpringMVC/) but it showing HTTP Status 404 – /SpringMVC/
    Additionally there is the red(i.e error) mark at first line of hi.jsp

    Please suggest……

  58. Thanks a lot!!!!!!!!!!!
    Its very helpful and running successful, awesome.

    Thank you very much!

  59. Hi Joe!

    Thanks a ton for such a wonderful explanation on Spring MVC. Its very Crisp and Simplified.
    Bless you. :)

  60. i’m using jboss server so what changes should i make in downloading jar file

  61. hi joe,
    which is the best book you think to learn spring?

    thanks in advance.

  62. I am trying to integrate spring with seam framework, can anybody help me with configuration for integrating.

    i can able to create spring service separately, i need help to integrate spring with seam.

    Thanks in advance
    Balaji

  63. Hey Joe….I new to your blog…
    the way you are explaining things and providing the example for same is amazing and very easy to get it….Its really nice material…
    Thanks and keep it up with good job…
    Now onwards i will be regular on it…
    Cheers
    :)

  64. Thanks you, now I understand how it works.

  65. Thanks..very understandable and simple documents

  66. Hi Joe, thanks a lot.
    very impressed with the information shared by you and your way of easy prsentation

  67. For a purchased domain name, where/how would I configure it to post to it rather than …localhost:8080… ?

  68. Superb Explanations !
    Looking for Spring MVC with Spring Security

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

ABOUT
I am Joe, author of this blog. I run javapapers with loads of passion. If you are into java, you may find lot of interesting things around.
Ads by Google
STAY in TOUCH:

Email:

Core Java | Servlet | JSP | Design Patterns | Android | Spring | Web Service | © 2008-2012 javapapers.