- 浏览: 65617 次
- 性别:
- 来自: 北京
-
文章分类
最新评论
-
elf8848:
引用好事坏事一起做。人吗,本来就复杂。
读了,很好,很强大. ...
做人的实话 -
feiyu367:
hi coreoak
有该spring mvc出处的链接地址吗 ...
spring MVC -
coreoak:
我晕, 怎么下载还需要注册!郁闷, 准备换地方了!
HTML学习教程 -
apple:
感谢楼主,francis@foxmail.com
Xquery学习资料目录(目前最全的资料pdf版本目录) -
Huaqingfly:
你好。楼主,麻烦帮我发一份:我的邮箱是:Huaqingfly@ ...
Xquery学习资料目录(目前最全的资料pdf版本目录)
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.
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.
相关推荐
在2015年的版本中,Spring MVC 4已经相当成熟,提供了许多特性来简化开发流程并提高开发效率。在这个"Mastering Spring MVC 4(2015.09)源码"中,我们可以深入理解这个框架的核心概念和实际应用。 首先,Spring MVC ...
本资源《精通Spring MVC4 电子版》将深入探讨这个框架的各个方面,旨在帮助开发者更好地理解和运用Spring MVC。 在Spring MVC中,模型由业务对象组成,视图负责展示数据,而控制器处理用户请求并协调模型和视图。这...
Spring MVC 4 Quickstart Maven Archetype 是一个快速启动模板,专为构建基于Spring MVC 4的无XML(no-xml)Web应用程序而设计。这个模板简化了开发过程,通过Maven构建工具帮助开发者快速搭建一个功能完备的Web应用...
下面,我们将详细介绍如何进行Spring MVC4与Mybatis的整合,并涉及相关的Jar包。 1. **Spring MVC4核心组件** - `spring-webmvc.jar`: 提供了Spring MVC的实现,包括DispatcherServlet、HandlerMapping、...
《精通Spring MVC4》这本书是Java开发者深入了解和掌握Spring MVC框架的重要参考资料。Spring MVC是Spring框架的一个核心组件,专门用于构建Web应用程序。本电子版详细介绍了Spring MVC4的各种特性和用法,帮助...
Spring MVC 4是该框架的一个版本,它在Spring 3.x的基础上增加了更多特性,提高了性能,并且与Spring 4.0的核心框架紧密集成。 在"springmvc4简单例子"中,我们通常会涉及到以下几个关键知识点: 1. **配置**:...
Spring MVC 是一个基于Java的轻量级Web应用框架,它为开发者提供了模型-视图-控制器(MVC)架构,使开发人员能够更好地组织和分离应用程序的业务逻辑、数据处理和用户界面。Spring MVC是Spring框架的一个核心组件,...
### Spring MVC 学习指南详解 #### 一、Spring MVC 概述 Spring MVC 是 Spring 框架的一部分,主要用于构建基于 Model-View-Controller (MVC) 设计模式的 Web 应用程序。它提供了丰富的功能来简化 Web 开发过程,...
Spring MVC和MyBatis是Java开发中常用的两个框架,它们分别负责Web层和持久层的管理。本资源提供了搭建Spring MVC 4.0与MyBatis整合应用所需的jar包,让我们来详细了解一下这两个框架以及它们如何协同工作。 Spring...
4. 创建请求处理器类,使用@Controller注解标识该类是一个控制器,使用@RequestMapping注解映射请求地址,处理请求的方法返回视图名称,Spring MVC会根据配置的视图解析器找到对应的JSP页面。 5. 使用@...
读书笔记:精通Spring MVC 4
Spring MVC和Hibernate是Java开发中两个非常重要的框架,Spring MVC用于构建Web应用程序的模型-视图-控制器(MVC)架构,而Hibernate则是一个对象关系映射(ORM)工具,帮助开发者将Java对象与数据库中的数据进行...
《Spring4Spring-MVC:整合Maven3、Spring4与Spring MVC 4的模板实践》 在现代Java Web开发中,Spring框架以其强大的功能和灵活性备受开发者青睐。本资源"Spring4Spring-MVc.rar"提供了一个基于Maven3、Spring4和...