Spring MVC4

9) Sample Application
9.1) Introduction

The final Section of this article details a Simple Contact Application that has provisions for Creating, Deleting and Listing Contact Objects. The aim of this Application is to show the various use of Controller Components like Abstract Controller, Abstract Command Controller and Form Controller along with Configuration Information.
9.2) The Web Descriptor File

As mentioned previously, since the Dispatcher Servlet acts as an Interceptor for the Client Request, an entry for the same has to be mentioned in the web.xml file. Follow is the code snippet for the same,

web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>

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

</web-app>


9.3) Configuration File

The following represents the Configuration File for holding various piece of Configuration Information. The first thing to note is the type of Handler Mapping configured. In our case, it is the Bean Name Url Handler Mapping which means that the Url of the Client is tightly coupled with the class name of the Bean (Controller). Since all the Jsp files are maintained in the '/WEB/contacts' directory the 'prefix' property is pointing to '/WEB/contacts'.

For the Create, Delete and List operation on Contacts, three different Controller Components have been defined. They are CreateContactController, DeleteContactController and ListContactsController respectively.

dispatcher-servlet.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

    <bean id="beanNameUrlMapping" class="org.springframework.web.servlet.handler.
    BeanNameUrlHandlerMapping"/>

    <bean name = "/CreateContact.htm" class="net.javabeat.articles.spring.mvc.
    contacts.CreateContactController">

        <property name="formView">
            <value>CreateContact</value>
        </property>
        <property name="successView">
            <value>ContactCreated</value>
        </property>   

    </bean>   

    <bean name = "/DeleteContact.htm" class= "net.javabeat.articles.spring.mvc.
    contacts.DeleteContactController">                   
    </bean>   

    <bean name = "/ListContacts.htm" class= "net.javabeat.articles.spring.mvc.
    contacts.ListContactsController">                   
    </bean>   

    <bean id="viewResolver" class="org.springframework.web.servlet.view.
    InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/contacts/"/>
        <property name="suffix" value=".jsp" />
    </bean>

</beans>


9.4) CreateContact and ContactCreated Jsp Files

The following is the code for CreateContact.jsp file.

CreateContact.jsp


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Create a Contact</title>
    </head>
    <body>

    <h1>Create a Contact</h1>

    <form name = "CreateContact" method = "get"">
        <input type = "text" name = "firstname" />
        <input type = "text" name = "lastname" />       
        <br>
        <input type="submit" name = "Create Contact" value = "Create Contact"/>
   </form>

</body>
</html>


Note that since this is the page that will be shown to the user initially, in the Configuration file, the property 'formView' is pointed to 'CreateContact'. Following is the code for ContactCreated.jsp. Since this is the View that will be shown after the Form Submission the property 'successView' is made to point to 'ContactCreated'.

ContactCreated.jsp


<html>
    <head>
    <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
    <title>Contact is Created</title>
    </head>

    <body>

    <h1>Contact is successfully Created</h1>

   </body>
</html>


9.5) DeleteContact.jsp

Following is the complete listing for DeleteContact.jsp file. Note that this Jsp File is mapped to DeleteContactController in the Configuration File.

DeleteContact.jsp


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Delete Contact</title>
    </head>
    <body>

    <h1>Delete Contact</h1>

    <form name = "DeleteContact" method = "get">
        <input type = "text" name = "firstname" />
        <br>
        <input type="submit" name = "DeleteContact" value = "Delete Contact"/>
    </form>

    </body>
</html>


9.6) ListContacts.jsp

This page is to list all the existing Contacts that were created before. It should be noted that the Model Object that holds all the Contact Information in the form of List is available in the ListContactsController. The Model Information from the Controller after getting bound to the Request Scope is being taken off from the View in the form of Expression Language.

Following is the listing for ListContacts.jsp

ListContacts.jsp


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Showing All Contacts</title>
    </head>
    <body>

    <h1>Showing All Contacts</h1>

    <p> The following are the created Contacts </p>

        <c:forEach items = "${allContacts}" var="contact">
            <c:out value="${contact.firstname}"/><br>
            <c:out value="${contact.lastname}"/><br>
        </c:forEach>

    </body>
</html>


9.7) Contacts.java

The following is the Class structure for Contacts.java for encapsulating the properties firstname and lastname.

Contact.java


package net.javabeat.articles.spring.mvc.contacts;

public class Contact {

    private String firstName;
    private String lastName;

    public Contact() {
    }

    public Contact(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    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;
    }

    public int hashCode(){
        return firstName.hashCode() + lastName.hashCode();
    }

    public boolean equals(Object object){
        if (object instanceof Contact){
            Contact second = (Contact)object;
            return (firstName.equals(second.getFirstName()) &&
                lastName.equals(second.getLastName()));
        }
        return false;
    }

    public String toString(){
        return "[First Name = " + firstName + ", Last Name = " + lastName + "]";
    }
}


9.8) ContactService.java

This simple service class provides functionalities for creating, deleting and listing the Contact information. All the Controller Components makes use of this class to achieve their respective functionalities.

ContactService.java


package net.javabeat.articles.spring.mvc.contacts;

import java.util.*;

public class ContactService {

    private static Map contacts = new HashMap();

    public ContactService() {
    }

    public static Contact createContact(Contact contact){
        contacts.put(new Integer(contact.hashCode()), contact);
        return contact;       
    }

    public static Contact createContact(String firstName, String lastName){
        return createContact(new Contact(firstName, lastName));
    }

    public static boolean deleteContact(String firstName){
        Iterator iterator = contacts.entrySet().iterator();       
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            Contact contact = (Contact)entry.getValue();           
            if (contact.getFirstName().equals(firstName)){
                contacts.remove(new Integer(contact.hashCode()));
                return true;
            }           
        }
        return false;
    }

    public static List listContacts(){
        return toList(contacts);
    }   

    private static List toList(Map contacts){
        List contactList = new ArrayList();
        Iterator iterator = contacts.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry)iterator.next();
            Contact contact = (Contact)entry.getValue();           
            contactList.add(contact);
        }
        return contactList;
    }
}


9.9) Controller Classes

Following is the listing for CreateContact Controller. Note that since the Model Information for creating a contact (for which the Client supplies the firstname and the lastname parameters) is the Contact class, call has been made in the Constructor to setCommandClass() by passing the class name of the Contact class.

CreateContactController.java


package net.javabeat.articles.spring.mvc.contacts;

import org.springframework.web.servlet.mvc.SimpleFormController;

public class CreateContactController extends SimpleFormController{

    public CreateContactController() {
        setCommandClass(Contact.class);
    }

    public void doSubmitAction(Object command){
        Contact contact = (Contact)command;
        ContactService.createContact(contact);
    }       
}


Note that the method doSubmitAction() doesn't return anything because the next Logical View to be displayed will be taken from the Configuration file which is represented by the property called 'successView'.

Following two classes are the Controller Components for Deleting and Listing Contacts. Note that in the case of Delete Operation, a Jsp Page (DeletedContact.jsp) containing information telling that the Contact has been Deleted will displayed. But since for the Contact Listing operation, the model information containing a Collection of Contact Objects has to be passed from the Controller to the View and the same is achieved in the 3 argument constructor to ModelAndView.

DeleteContactController.java


package net.javabeat.articles.spring.mvc.contacts;

import javax.servlet.http.*;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

public class DeleteContactController extends AbstractCommandController{

    public DeleteContactController(){
        setCommandClass(Contact.class);
    }

    public ModelAndView handle(HttpServletRequest request,
        HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        Contact contact = (Contact)command;
        ContactService.deleteContact(contact.getFirstName());
        return new ModelAndView("DeletedContact");

    }
}


Here is the listing for ListContactsController.java.

ListContactsController.java


package net.javabeat.articles.spring.mvc.contacts;

import java.util.List;
import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class ListContactsController extends AbstractController{

    public ListContactsController() {
    }

    public ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception{

        List allContacts = ContactService.listContacts();
        return new ModelAndView("ListContacts", "allContacts", allContacts);

    }
}


10) Conclusion

The Article provided a basic Introduction over the core concepts in Spring MVC for the Web Tier. Since the Spring Web Tier is built on top of the Spring Core Layer all the functionalities like Bean Lifecycle Management, Dependency Injection etc. will be automatically available to the Bean Components. Starting off with the Interactions that will take place when a Client Request for a Resource, it pointed out the various micro-level activities that take place in that Work flow. Then the Core Components of Spring like Dispatcher Servlet, Controllers, Model/View, Handler Mappings, Handler Adapters and View Resolvers are also discussed briefly. Finally the article ended up with the Simple Contact Application that demonstrated the usage of the various types of Controllers.

你可能感兴趣的:(spring,jsp,mvc,Web,servlet)