Wednesday, August 29, 2012

Spring MVC tutorial

Before Starting, I believe you must have basic idea about JAVA, SPRING and Spring MVC.

For Spring MVC :

In this tutorial , I will just tell you what are the basic thing that you need to start MVC.

Step 1 : Create a class 

public class HelloWorld {
    public String helloWorld() {
         return = "Hello World, Spring 3.0!";

1 . The class HelloWorld  has the annotation @Controller and @RequestMapping("/hello"). When Spring scans this class, it will recognize this bean as being a Controller bean for processing requests. 2 .The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /hello in the URL path.

Step 2. Mapping Spring MVC in WEB.xml

The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml.

<!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->


<!-- This loads the root webapp Spring context -->


Note that I have mapped /rest/* url pattern with example DispatcherServlet. Thus any url with /rest/* pattern will call Spring MVC Front controller.

                  The REST call would be http://ip:port/rest/hello

If your controller class has some dependency which you have defined in your spring context file.Then you have to load it in <context-param>.(red line).
Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. I have created the file named spring-servlet.xml

3 . Spring Configuration file

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi="" xmlns:task=""
    xmlns:tx="" xmlns:context=""
    xmlns:mvc="" xmlns:util=""

    <!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />

    <!-- class name of the controller or If you have package use component-scan -->
    <bean class="com.waheed.spring.hibernate.HelloWorld" />


The highlighted red line allow Spring to load the components from class. This will load our HelloWorld class.

Congratulation..!!! You are done here...

Download source code :