Thursday, May 29, 2014

Spring MVC

Introduction:
              Spring MVC has the most flexible architecture to develop web applications in java/spring environment.It provides clear separation of different layers components, with this MVC Architecture we can use different types front-end technologies like Jsp,freemaker etc.

Basic architecture and flow of Spring MVC Architecture


Dispatcher Servlet: 'Dispatcher Servlet'  which receives  requests and forward them to controllers and also allows to use Other all Features.It traps and takes the requests  and dispatches them to the appropriate controllers with the help of Handler Mappings.

Handler Mapping: Handles the execution of a list of pre-processors and post-processors and controllers if they match certain(Ex: matching URL specified with a controller).It maps requests with Intended Controllers.

Controller: Controller interpret user input and transforms it into a model that represented to the user by View. It serves the user requests and returns Model and View Object.

ViewResolver:  resolves view names to views.

View:  A view is a generated HTML output to the User.

Lets take an Example to explain flow of Spring MVC.

1. Take a new DynamicWebApplication in your IDE with name 'Spring3MVC'.
                       

    
2. go to WEB-INF  Folder and Add the following code to web.xml file.

 <!-- Dispatcher Servlet -->    <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.htm</url-pattern>
  </servlet-mapping>

By adding the above code we are configuring the 'DispatcherServlet'  or Front Controller which controls the entire application execution flow of control.

3. Next add some list of jar file as shown below in lib Folder.
          
     

I am using spring 3.2.2 in my application.you can get 'commons-logging.jar' from spring 2.5 and download 'jstl.jar' .

4.Add a Controller class to service/process client request.
In my application i want to display some 'hello world ' kind of message so i use my     Controller to do this.add this controller in some package like 'com.controller'

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

   @RequestMapping("/hello")
   public ModelAndView helloWorld() {

       String message = "Hello World, Spring 3.2.2..!!";
       return new ModelAndView("hello", "message", message);
   }
}


In the above code there are 2 Annotations
  •       @Controller
  •       @RequestMapping("/hello")
 @Controller-tells to spring that this bean is a Controller bean to process client  
                         requests.
@RequestMapping("/hello")-tells to spring that this bean should process all the requests beginning  with '/hello'. 

This controller returns Model and View Object with a message ''Hello World, Spring 3.2.2..!!".

5. To display this result to the client we need View.we are using jsp in view layer. So we have to create a jsp with name hello.jsp. place this jsp file in WEB-INF/jsp folder.

    

the code in hello.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>hello</title>
    <title>Spring 3.2.2 MVC: Hello World</title>
</head>
<body>
    ${message}
</body>
</html>

This 'message' displays Hello World, Spring 3.2.2..!! ,Because message is the name in Model and View Object which return by the Controller.

And also we need one more jsp to send request, for this take a jsp with name 'index.jsp' and place in in /WEB-INF/jsp/ Folder.


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring 3.2.2 SpringMVC</title>
</head>
<body>
    <a href="hello.htm">demo request</a>
</body>
</html>

make this 'index.jsp' as the welcome file for Application,to do this add following code to web.xml file.

<display-name>Spring3MVC</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
  </welcome-file-list>

Finally we need spring bean configuration file with name 'springmvc-servlet.xml'. Because when DispatcherServlet initialized it looks for file with name [value of <servlet-name> tag in DispatcherServlet configuration]-servlet.xml in WEB-INF Folder.So in our example the spring bean configuration file name should be ''springmvc-servlet.xml".

This file contains Handler Mappings, ViewResolvers, Controllers and Other Spring Bean configuration.
our file contains

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

     <context:component-scan  base-package="com.controller" />
       
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
   </beans>

The '<context:component-scan  base-package="com.controller" />' tag tells Spring to load components from 'com.controller' package and it's sub packages.
The ViewResolver  bean resolves the view and add prefix  '/WEB-INF/jsp/' and suffix '.jsp' . In this app Controller HelloWorldController have return Model and View Object with view hello ,this resolver resolves that to '/WEB-INF/jsp/hello.jsp'.

Final structure of Application
                  


Flow:
1. request sent from index.jsp.

2. DispatcherServlet traps and Takes the request and dispatches it to Controller HelloWorldController by looking at HadlerMapping(this was done by annotations).

3. Controller HelloWorldController process use request and returns a Model and View Object with View name hello and other details.

4. DispatcherServlet resolves the view name to '/WEB-INF/jsp/hello.jsp' by looking at into ViewResolver Configuration in Spring bean configuration file springmvc-servlet.xml. The hello.jsp rendered by the spring and send to the client.

That is the end of Spring MVC First App.


0 comments:

Post a Comment