Hello World Example with annotation driven Spring 3 MVC in Eclipse

In this java tutorial, we will learn the most innovative java framework at this time, that is Spring Web MVC framework, works and how we can very easily create our web applications with it. We will go through a hello world spring mvc example in eclipse to illustrate how this java framework work with mvc pattern.

In this example, we will print a small hello world message using java spring. I am using Spring MVC 3.0.3 release, Eclipse 3.7 and Tomcat 6 as server.

First of all create a dynamic web project in eclipse. Click on New Project and the Dynamic Web Project.

Select Dynamic Web Project

Select Dynamic Web Project

Then Eclipse will ask you to enter name of the project. Enter the name of the project and click on finish.

Provide Project Name

Provide Project Name

Eclipse will create a dynamic web project for you with specified name. After the finish of creating dynamic web project, we have to add Spring Web MVC based jars to our project in eclipse. The jars should be added to the lib directory under WEB-INF in the project. The following jars should be added to the project :

  • commons-logging-1.1.1.jar
  • jstl-1.2.jar
  • spring-asm-3.0.3.RELEASE.jar
  • spring-beans-3.0.3.RELEASE.jar
  • spring-context-3.0.3.RELEASE.jar
  • spring-context-support-3.0.3.RELEASE.jar
  • spring-core-3.0.3.RELEASE.jar
  • spring-expression-3.0.3.RELEASE.jar
  • spring-web-3.0.3.RELEASE.jar
  • spring-webmvc-3.0.3.RELEASE.jar

You can download these jar files from Spring Source site or you can download war file of this tutorial which contains all above jar files.

next we have to follow some steps for the implementation of our example. Following are the steps to be followed :

  1. First of all, we have to enable Spring Web MVC framework for our application, so that the requests come to the server are goes through the spring mvc flow. To enable Spring MVC, we have to register org.springframework.web.servlet.DispatcherServlet provided in spring jars in our applications web.xml.
  2. After that we will create configuration files (app-config.xml) for Spring MVC. The configuration file will contain information about controller class, view resolvers, message resources etc. app-config.xml will configure the spring mvc form annotation configuration.
  3. Then we will create our controller class (HelloWorldAction.java) that will handle the request to print hello world in jsp view.
  4. At the last we will implement the view part (hello.jsp) of the application that will show the hello world message.

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>HelloWorldExampleWithSpring3MVCInEclipse</display-name>
    <servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/app-config.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

To activate Spring MVC, we register DispatcherServlet in our web.xml with the path “*.htm” assigned to it. I have also mention the spring configuration file name and position as a init-param with name “contextConfigLocation“. Spring will locate this file and load the configurations on start up.

app-config.xml

app-config.xml is the configuration file for spring web mvc framework. The name of the file may be different in any application but if you do not specify the init-param with name “contextConfigLocation“, spring mvc will search for the file name <Servlet-name>-servlet.xml Following is the code in our configuration file :


<?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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.raistudies" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />
    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

Here “xmlns” entries says that the file will configure three components “beans“, “context” and “mvc“. Spring components “beans” and “context” are related to Spring IoC functionality that works for dependency injection. “mvc” components are related to the spring web mvc framework.

  1. <context:component-scan base-package=”com.raistudies” /> : context:component-scan says that we will use annotation driven configuration for Spring IoC components in our application. base-package=”com.raistudies” says to spring scanning the classpath for IoC components under the package “com.raistudies“.
  2. <mvc:annotation-driven />: indicated that the mvc components are also annotation driven and components will be present in context package means in “com.raistudies
  3. We have also registered an viewResolver of type “org.springframework.web.servlet.view.InternalResourceViewResolver“. Spring will automatically configure it as a view resolver component and when any spring controller will return a view name it will check for the view definition with the class “org.springframework.web.servlet.view.InternalResourceViewResolver“. InternalResourceViewResolver class takes two special parameters prefix and suffix. The value of these parameters are applied to the view name to get actual location of the view. For example, say spring controller returns the view name as “hello” and prefix is defined as “/WEB-INF/jsp/” and suffix is defined as “.jsp” the InternalResourceViewResolver will return the jsp “/WEB-INF/jsp/hello.jsp” to the browser.

Spring can handle two types on configuration : firstly xml based and second one is annotation based. Here we will use annotation driven configuration. Latter on we will see an example of using xml driven configuration for same example.

HelloWorldAction.java

Following is HelloWorldAction :


package com.raistudies.actions;

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.servlet.ModelAndView;

@Controller
public class HelloWorldAction {

    @RequestMapping(value="/hello",method=RequestMethod.GET)
    public ModelAndView sayHello(Model model){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello");
        model.addAttribute("HelloMessage", "Hello World from My First Spring 3 mvc application");
        return mv;
    }
}

In Spring 3 MVC any java pojo class can be controller. We just have to annotate it with @Controller, then spring will automatically make it a mvc controller. In our controller class, there is a sayHello which takes instance of Model as an argument and returns instance of ModelAndView instance. The method sayHello is also annotate with @RequestMapping(value=”/hello”,method=RequestMethod.GET). @RequestMapping indicates that the method sayHello is request handler and will be invoked when the ulr “/hello” of request type GET will be come to server.

In Spring 3 MVC, Model class represents a model in mvc model and stores values that we want to carry to the view. As, we have added an value of key “HelloMessage” and value “Hello World from My First Spring 3 mvc application”, we can print this value is any jsp.

ModelAndView class contains the detail of the view and model in spring mvc. We add view to be display to ModelAndView instance and return it.

hello.jsp

In our view hello.jsp, we have just print the model attribute “HelloMessage” that we have added in our controller class. Following is the code of hello.jsp :


<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ page session="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Hello World with Spring 3 MVC</title>
    </head>
    <body>
        <h1>Welcome! Spring MVC is working well.</h1><br />
        ${HelloMessage}
    </body>
</html>

We have used jstl for writing the value to jsp.

Export the project as war, deploy the war to the Tomcat 6 and hit the url in browser you will get following view :

Spring 3 MVC Hello World

Spring 3 MVC Hello World

The project directory in eclipse will look like this :

Spring 3 MVC Project DirectoryHierarchy

Spring 3 MVC Project DirectoryHierarchy

Waiting for your feedback……:)

You can download our example code and war from bellow links :

Code : Download

War : Download

Related Posts:

Leave a comment ?

2 Comments.

  1. hi Rahul,
    I am beginner with java and and needs to addapt myself with spring quickly for a new project in my comp.
    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 able to print, “Welcome! Spring MVC is working well.” but not the next line below it, as pe rur example.
    Am getting error in these import statements,
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    and on this annotation,
    @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

Leave a Comment Cancel reply


NOTE - You can 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>