MultiActionController 可以处理多个请求,将数据绑定到Command中,可以在代码中减少类似request.getParameter("")的语句。如果能在MultiActionController的子类中使用Command就更好了。步骤如下:
第一步:配置整个环境,有4个配置配置文件:web.xml,<servlet-name>-servlet.xml,applicationContext.xml,persistence.xml,具体配置如下
1. web.xml
<?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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>test-maven</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/page/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
2. spring-servlet.xml
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置视图解析 -->
<bean id="viewresolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/user.htm">userController</prop>
</props>
</property>
</bean>
<!--方法名解析器-->
<bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>method</value>
</property>
</bean>
<bean id="userController" class="com.test.springmvc.controller.UserFormController">
<property name="methodNameResolver">
<ref bean="methodNameResolver"/>
</property>
</bean>
</beans>
3. applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="oracleDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
<property name="username" value="invoice" />
<property name="password" value="invoice" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="oracleDataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.TopLinkJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform"
value="oracle.toplink.essentials.platform.database.oracle.OraclePlatform" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean class="com.test.springmvc.util.MyClassLoader" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- Dao的实现 -->
<bean id="userDao" class="com.test.springmvc.dao.impl.UserDaoImpl">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
4. persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="invoice">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.test.springmvc.bean.User</class>
<!-- <properties>
<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
<property name="hibernate.connection.url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
<property name="hibernate.connection.username" value="invoice" />
<property name="hibernate.connection.password" value="invoice" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties> -->
</persistence-unit>
</persistence>
第二步:页面 index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>welcome Page</title>
</head>
<body>
<form:form action="./user.htm?method=login" method="post">
<table align="center">
<tr>
<td><font color="red"> ${msg } </font></td>
</tr>
<tr>
<td>username:
<%-- <spring:bind path="user.userName"></spring:bind> --%>
<%-- <form:input path="userName" /></td> --%>
<input name="userName"> <%--userName 是POJO中的属性--%>
</tr>
<tr>
<td>password:
<%-- <spring:bind path="user.userPassword"></spring:bind>--%>
<%-- <form:input path="userPassword" /> --%>
<input name="userPassword"> <%--userPassword 是POJO中的属性--%>
</td>
</tr>
<tr>
<td><input id="submit" type="submit" value="submit" /></td>
<td><input id="reset" type="reset" value="reset" /></td>
</tr>
</table>
</form:form>
<br />
<form action="./user.htm?method=login" method="post">
<table>
<tr>
<td><input id="submit" type="submit" value="login" /></td>
<td><input id="reset" type="reset" value="reset" /></td>
</tr>
<tr>
<td><a href="./user.htm?method=add">add</a>
</td>
</tr>
</table>
</form>
</body>
</html>
第三步:MultiActionController子类
package com.test.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.test.springmvc.bean.User;
import com.test.springmvc.service.UserService;
public class UserFormController extends MultiActionController {
public UserFormController() {
}
public ModelAndView login(HttpServletRequest req, HttpServletResponse resp) throws Exception {
System.out.println("***********in login method*******************");
/**
* 以下两句的作用是将 req 中的参数绑定到 POJO User中去
*/
User user = (User) newCommandObject(User.class);
bind(req, user);
// User user = (User) command;
if (user != null) {
System.out.println("********user is not null**********");
System.out.println("********username is:****"+user.getUserName());
}
String msg = "Well Done, this is very important task you finished";
ModelAndView modelAndView = new ModelAndView("main");
modelAndView.addObject("msg", msg);
return modelAndView;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("***********in add method*******************");
return null;
}
}
第四步: POJO (User.java)
package com.test.springmvc.bean;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the user database table.
*
*/
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="user_id")
private int userId;
@Column(name="user_name")
private String userName;
@Column(name="user_password")
private String userPassword;
public User() {
}
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return this.userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
至此,整个应用的流程已经走完。
===============================总结==============================
想要在MultiActionController中使用Command,在网上有很多,但是都不能work。经过这次配置,总结起来,关键的是两点:
1. 在Page中form中的数据name为POJO的属性 (文中为User的属性)
2. 在MultiActionController的子类中,
首先 使用newCommandObject(Class)方法创建Command对象
然后 调用MultiActionController的bind(request,Command)方法,将request中的数据绑定到command中