Tuesday, 8 April 2014

Spring Framework - PART - II - Spring MVC

In this discussion ,I'll be focussing on spring MVC .

  • As the name suggests spring MVC is made around model , view and controller or in another words ,  it is the web component of spring framework . 
  • It provides the functionality to make web applications .
  • spring framework can be integrated easily with other web frameworks like struts . There is no tight coupling between spring and other web frameworks.
Table of Contents :-

  • Basic Introduction
  • Workflow of spring MVC 
  • Features 
  • Configuration
  • Implementing Controllers
  • Small application with spring framework - GET request handling
  • Form handling - POST request

Basic Introduction :- 
Root of spring MVC framework is DispatcherServlet that dispatches the request to handlers or controllers , that leads to the development of spring web application.
                       
                                         
                                                                                                                 

Workflow of spring MVC :- 
The spring model-view-controller is designed around a dispatcher servlet that is responsible for handling http request and response cycle.Few steps to handle request and response cycle are :-
  • When request comes to Dispatcher Servlet , it consults to handler mapping to find the appropriate controller.
  • Controller takes the request and call the appropriate service method based on GET or POST request.
  • Service method set the model based on business logic and returns view name to Dispatcher Servlet.
  • Servlet then consults the view resolver to get the view.
  • View is then rendered to the client.
Features :- 

  • It provides support for REST based web services
  • It provides annotation based configuration support.
  • It allows any number of request handling methods.
  • It does not have any interface or base class requirement.
Configuration :-
As first of all request comes to Dispatcher servlet so we need to set up the dispatcher servlet in web.xml file .

 <?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>Spring3-Hibernate</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>springhibernate</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springhibernate</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

In above example we have defined servlet name(<servlet-name>) and mapping (<url-pattern>) that it'll handle.

springhibernate-servlet.xml 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:aop="http://www.springframework.org/schema/aop"

    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
  <context:component-scan base-package="com.mycompany.app.user.controller" />
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>
  • Upon initialization of Dispatcher servlet , framework looks for the file named [servlet-name] -servlet.xml file in the WEB-INF directory. i.e. springhibernate-servlet.xml file as shown above.
  •  In springhibernate-servlet.xml   we have used InternalResourceViewResolver that have the internal rules for rendering view . e.g. If handler return hello then according to suffix (".jsp") hello.jsp view will be render that is located in (/WEB-INF/jsp) i.e. defined in prefix.
  • Before moving to application we should have knowledge about @controller , @RequestMapping ,@PathVariable annotations . How these annotations works during request response cycle.
Implementing controllers :- 

MVC controller provided annotation based programming model that uses annotations such as @RequestMapping , @PathVariable , @ModelAttribute etc. 
I have taken the example of my controller which i have made in my application :-

@Controller
public class userController {
    @Autowired
    private userService userService;
    @RequestMapping("/index")
    public String listUsers(Map<String, Object> map) {
        map.put("user", new user());
        map.put("userList", userService.listUser());
        return "user";
    }
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("user")
    user user, BindingResult result) {
    userService.addUser(user);
        return "redirect:/index";
    }
    @RequestMapping("/delete/{userId}")
    public String deleteUser(@PathVariable("userId")
    Integer userId) {
    userService.removeUser(userId);
        return "redirect:/index";
    }
}

Defining a controller with @Controller :- 
  • @Controller annotations describes that particular class is playing the role of controller.  and in Spring we do not have to extend any base class controller.
  • In [servlet-name]-servelet.xml file we define a tag to scan the controller as :-                  <context:component-scan base-package="com.mycompany.app.user.controller" />    
  •  So, dispatcher scans controller classes define with @controller annotation and detects for another annotations.
@RequestMapping  :-
  • To map the URLs , we use @RequestMapping annotation . It can be use with handler or particular method.
  • As in above example , @RequestMapping is used in many places . 
  • First usage in listUsers method . It means this method will handle the request that will have URL like :-   localhost:8080/springhibernate/index
  • Second usage in addUser Function . It means this method will handle the request that will have URL like :-   localhost:8080/springhibernate/add
  • Third usage in deleteUser. This method will handle the request that will have URL like :- localhost:8080/sprinhghibernate/delete/12 , where 12 = {userId}
@ModelAttribute :- 
  • In addUser Function we have user @ModelAttribute annotation . and also this method has POST request . During POST request we bind the form data with @ModelAttribute  annotation . It specifies the method arguments that is passed from the Form. 
  • In above example, I have passed the user information that is filled into form .
@PathVariable:-
  • It indicates that the meethod paramater is bound to the URI template variable.
  • In above example, userId will get from the URI : - localhost:8080/springhibernate/delete/12 , here userId =12
Small application with spring framework - GET request handling :- 
Before starting an application we should have following :-
  • Eclipse
  • Tomcat
  • JDK
Our goal it to print hello world .

Getting Started :- 

  • create a maven project , write the command as :-

mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
  • To convert maven project to support eclipse IDE , issue the command :-

mvn eclipse:eclipse
  • Now Import the project into eclipse.
  • Next step is to adding dependency into pom.xml file :-

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>springMVC</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
<properties>
     <org.springframework.version>3.0.2.RELEASE</org.springframework.version>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.0</version>
<configuration>
<!-- Directory for Web application-->
<webappDirectory>webapp</webappDirectory>
<webResources></webResources>
</configuration>
</plugin>
</plugins>
<finalName>springMVC</finalName>
</build>
  <name>springMVC</name>
  <url>http://maven.apache.org</url>
 <dependencies>
   <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework.version}</version>
    </dependency>
    <dependency>
  </project>

As I stated before , first of all request comes to dispatcher servlet ,so we have to define the dispatcher servlet name and url-pattern in web.xml file.

<?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>SpringMVC</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <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>/</url-pattern>
    </servlet-mapping>
</web-app>

Next step is to make springMVC-servlet.xml file in WEB-INF folder. and as i explained earlier , in this file i'll define context-scan base package and internalviewresolver bean that will have prefix and suffix properties for the view name. As shown below :-

springhibernate-servlet.xml 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:aop="http://www.springframework.org/schema/aop"

    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<context:annotation-config />
  <context:component-scan base-package="com.mycompany.app.user.controller" />
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

Next step is to make controller file :-

package com.mycompany.app.user.controller;

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

@Controller
public class userController {
  @RequestMapping("/welcome" , method=RequestMethod.GET)
    public String showWelocme(ModelMap model) {
        model.addAttribute("message","Hello world");
        return "hello";
    }
 }

  • When controller will return the hello to the dispatcher servlet , then it'll consult the view resolver to find the appropriate view . View resolver then render the particular view to the client. 
  • As we have defined in the dispatcher servlet xml file(i.e. springhibernate-servlet.xml) file, Internalviewresolver will find out the hello.jsp file in WEB-INF/jsp folder. and render it to the browser.
  • So next step is to make hello.jsp file in WEB-INF/jsp folder.
hello.jsp file :-

<html>
   <body>
   <h2>Message : ${message}</h2>
   </body>
</html>

  • Next step is to deploy the war on tomcat and restart the server. 
  • Hit the  url :- localhost:8080/springMVC/welcome.
  • Message will display i.e. Hello world
This is what about GET request.

Form Handling - POST request :-

  • In this example i'll show web application which make use of html forms using spring framework .
  • Make the configuration files i.e. web.xml  and  servlet file  as i stated above in first example.
  • Next step is to create an entity file , controller and jsp file.
Entity file :-

package com.mycompany.app.user.form;


public class user {
private Integer id;
 private String firstname;
 private String lastname;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

}

Controller File :-

package com.mycompany.app.user.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;

@Controller

public class userController {

   @RequestMapping(value = "/user", method = RequestMethod.GET)

   public ModelAndView user() {
      return new ModelAndView("user", "command", new user());
   }
   
   @RequestMapping(value = "/adduser", method = RequestMethod.POST)
   public String addUser(@ModelAttribute("SpringWeb")user user, 
   ModelMap model) {
      model.addAttribute("firstname", user.getFirstname());
      model.addAttribute("lastname", user.getlastname());
      model.addAttribute("id", user.getId());
      
      return "result";
   }

}

In controller file we have 2 functions :-

  1. First is user() function that has ModelandView return type. Request Mapping for this function is /user .i.e. when we will hit the locahost:8080/springWeb/user then user.jsp view will be render. Next is the command object , when we use<form:form> tag in jsp file then spring framework expects command object.
  2. Second is addUser() , The request mapping for this function is /adduser and RequestMethod is POST. During POST request , here we are using @ModelAttribute to set the form data in user. 


  • Next step is to make user.jsp file and result.jsp file.
  • user.jsp file for form and result.jsp file to show the data that we'll fill into the form.

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>User Info</h2>
<form:form method="POST" action="/HelloWeb/addUser">
   <table>
    <tr>
        <td><form:label path="firstname">First Name</form:label></td>
        <td><form:input path="firstname" /></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Last Name</form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
        <td><form:label path="id">id</form:label></td>
        <td><form:input path="id" /></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>  
</form:form>
</body>
</html>

result.jsp  file :-

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Submitted User Information</h2>
   <table>
    <tr>
        <td>First Name</td>
        <td>${firstname}</td>
    </tr>
    <tr>
        <td>Last Name</td>
        <td>${lastname}</td>
    </tr>
    <tr>
        <td>ID</td>
        <td>${id}</td>
    </tr>
</table>  
</body>
</html>

This is what about handling forms in spring framework. 

 For further details about spring with hibernate you can read to my next tutorial(in progress).


























2 comments:


  1. w

    It is integrated on MS Windows server to facilitate creation of varied web-based applications. These applications facilitate file gathering, sharing, management and storage.




    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery





    ReplyDelete