Monday 14 October 2013

Spring 3 MVC hello world application with maven

Posted by Kanhaiya
Before you start this Spring 3 MVC tutorial, please refer to this new features in Spring 3 documentation, so that you have a brief idea of what’s new in Spring 3.

In this tutorial, I am building hello world application using spring 3 (mvc) framework. Follow the given steps and learn the basics.

Technologies used :
  1. Spring 3.1.2.RELEASE
  2. JDK 1.6
  3. Maven 3
  4. Eclipse 3.6
  5. Maven Integration for Eclipse WTP

Step 1. Create a Dynamic Web Project
When you create adynamic web project in eclipse then by default it showing this


Then remove this src folder and add new folders like this src/test/java, src/test/resources, src/main/java, src/main/resources


Then click next then by default it showing this


Change the "Content directory" name WebContent to webapp then finish it.

We are following this process because here we are creating maven web project. Every maven project follow this standard directory structure .

Then right click on project go for configure option and convert it into maven project with select WAR option because you create a web project. It create a entry of pom.xml.

Step 2. Add Project Dependencies in pom.xml
Add dependency of Spring MVC 3 in Maven pom.xml.
http://maven.apache.org

 
  3.1.2.RELEASE
 

 
  
  
   org.springframework
   spring-webmvc
   ${org.springframework.version}
  
 
Note : Spring MVC depends on spring-core, spring-beans, spring-context, spring-web. If we add 'spring-webmvc' dependency in pom.xml then all the required dependencies / libraries will be automatically downloaded and added to the project's classpath by Maven.

Step 3.
Open command prompt and go to current working project directory path as you created. Now execute below command.
mvn clean install
mvn eclipse:eclipse
mvn resources:resources


By this command it will download all dependencies to maven local repository and include them in project build. After that all these dependencies (all jars) copy in src/main/webapp/WEB-INF/lib from target project

Step 4. Controller Class and Request Mapping
Create a spring controller class called SpringMVCHelloController in package 'com.kanha.controller' and copy following code into it.
/**
 * 
 */
package com.kanha.controller;

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

/**
 * @author kanhaiya.sahu
 *
 */
@Controller
public class SpringHelloWorldController {
 
 @RequestMapping("/")
 public String printHelloWorld(Model model) {
  model.addAttribute("message", "Spring MVC Hello World Example By Kanhaiya!");
  return "helloWorld";
 }

}
@Controller annotation indicates that this class serves the role of a controller. The Servlet dispatcher scans @Controller annotated Controller classes for mapped handler methods and detects @RequestMapping annotations.
@RequestMapping annotation specifies that this handler method will process all requests beginning with '/' in the URL and return the logical view name.
'org.springframework.ui.Model' object is a map which is passed by the Spring container while invoking the handler method 'printHelloWorld'. The message string has been added to 'Model' object against the key 'message'. This model object is available in the view. We can use the key 'message' to get the value and display the same in the UI.

Step 5. Create a JSP page as View
Now we need to create a JSP page called helloWorld.jsp under 'WEB-INF/pages' directory and copy the following jsp file content. We have used the key 'message' in expression '${message}' to get the value and display the same in 'helloWorld.jsp'.
<%@ page language="java" caontentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 

  
  Spring MVC Hello World Example Using Maven  


${message}


Step 6. Add Spring Configuration File
Create an xml file called dispatcher-servlet.xml under 'WEB-INF' directory and copy the following content.



    
    
    
 
  
  
 

The above configuration file provides context information to the Spring container. '<context:component-scan>' enables the auto-detection of annotated components (like Controller, Service etc). So spring container will scan and load all the annotated component (e.g. SpringMVCHelloController) from the package 'com.kanha.controller' and it's subpackages.

'<mvc:annotation-driven />' specifies that we are using annotation based configuration.

ViewResolver provides a mapping between logical view name and actual view. It enables us to render models in UI without tying us to a specific view technology like JSPs, JSF, Velocity templates etc. Handler method defined in Controller class must resolve to a logical view name. In our case, 'printHelloWorld' handler method returns 'helloWorld' view name. It gets resolved to the path 'WEB-INF/pages/helloWorld.jsp' by the 'InternalResourceViewResolver' by adding prefix '/WEB-INF/pages/' and suffix '.jsp' to the view name 'helloWorld'.

Step 7. Integrate Spring with Web Application


 SpringMVCHelloWorld

 
  dispatcher
  org.springframework.web.servlet.DispatcherServlet
  1
 
 
  dispatcher
  /
 


DispatcherServlet (Front Controller) is mapped with the '/'. Upon initialization of the DispatcherServlet, Spring MVC looks for a configuration file called [servlet-name]-servlet.xml under the WEB-INF directory and creates the beans defined there. In our case the file is 'dispatcher-servlet.xml'.

Step 8. Overall Project Structure


Step 9. Deploy and Run the Application
Right click on the project 'SpringMVCHelloWorld' and select from context menu 'Run As' --> 'Run on Server'. Select the existing tomcat server. The web application will be deployed in the tomcat web server and a browser will be opened with 'Hello World!' message as shown below



Download Source Code with lib
SrcCodes : SpringMVCHelloWorld.zip


No comments:

Post a Comment