Spring MVC流程说明:
用户向Web服务器发送请求
Web服务器根据web.xml文件找到请求映射到的Contorller处理器。
处理器根据请求访问业务Service层和DAO层进行处理然后把得出的返回结果到前端JSP页面
用户通过返回结果得到相应的信息
项目配置文件如下:
Web.xml:
<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">
<!-- 配置 Spring的 IOC 容器: 配置文件、监听器 -->
<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>
<!-- 配置 SpringMVC 的 Servlet -->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filte-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
db.properties:
user=root
password=1204
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
SpringMVC配置文件:
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="springmvc"></context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="suffix" value=".jsp"></property>
<property name="prefix" value="/"></property>
</bean>
Spring 配置文件:
<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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:component-scan base-package="springmvc"></context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置 C3P0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property name="driverClass" value="${driver}"></property>
<!-- 当连接池中的连接用完时,C3P0一次性创建新连接的数目-->
<property name="acquireIncrement" value="5"></property>
<!-- 初始化时创建的连接数,必须在minPoolSize和maxPoolSize之间 -->
<property name="initialPoolSize" value="10"></property>
<property name="maxPoolSize" value="20"></property>
<property name="minPoolSize" value="5"></property>
<!-- jdbc的标准参数 用以控制数据源内加载的PreparedStatement数量,但由于预缓存的Statement属于单个Connection而不是整个连接 -->
<property name="maxStatements" value="20"></property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
源码:
Customer:
package springmvc.model;
public class Customer {
private Integer id;
private String name;
private String address;
private String phone;
public Customer(Integer id, String name, String address, String phone) {
this.id = id;
this.name = name;
this.address = address;
this.phone = phone;
}
public Customer() {
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + ", phone=" + phone + "]";
}
}
CriteriaCustomer:
package springmvc.model;
public class CriteriaCustomer {
private String name = "";
private String address = "";
private String phone = "";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public CriteriaCustomer(String name, String address, String phone) {
this.name = name;
this.address = address;
this.phone = phone;
if(this.name == null){
this.name = "";
}
if(this.address == null){
this.address = "";
}
if(this.phone == null){
this.phone = "";
}
}
public CriteriaCustomer() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "CriteriaCustomer [name=" + name + ", address=" + address
+ ", phone=" + phone + "]";
}
}
DAO:
package springmvc.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class DAO {
private JdbcTemplate jdbcTemplate;
@Resource
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
private Class<T> clazz;
@SuppressWarnings("unchecked")
public DAO() {
Type type = getClass().getGenericSuperclass();
if(type instanceof ParameterizedType){
ParameterizedType pt = (ParameterizedType) type;
Type [] parameterArgs = pt.getActualTypeArguments();
if(parameterArgs != null && parameterArgs.length > 0){
if(parameterArgs[0] instanceof Class){
clazz = (Class<T>) parameterArgs[0];
}
}
}
}
protected void update(String sql, Object ... args) throws SQLException{
jdbcTemplate.update(sql, args);
}
protected T get(String sql, Object ... args) throws SQLException{
return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<T>(clazz), args);
}
protected List<T> getForList(String sql, Object ... args) throws SQLException{
return jdbcTemplate.query(sql, new BeanPropertyRowMapper(clazz), args);
}
protected <E> E getValue(String sql, Object ... args) throws SQLException{
E result = null;
List list = jdbcTemplate.queryForList(sql, args);
if(list != null && list.size() > 0){
Map map = (Map) list.get(0);
result = (E) map.values().iterator().next();
}
return result;
}
}
CustomerDAO:
package springmvc.dao;
import java.util.List;
import springmvc.model.CriteriaCustomer;
import springmvc.model.Customer;
public interface CustomerDAO{
public void save(Customer cust);
public void delete(Integer id);
public void update(Customer cust);
public List<Customer> getForList(CriteriaCustomer cc);
public Customer getCustomer(Integer id);
public long getCountWithName(String name);
}
CustomerDAOImpl:
package springmvc.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.springframework.stereotype.Repository;
import springmvc.dao.CustomerDAO;
import springmvc.dao.DAO;
import springmvc.exception.CustomerNameExistException;
import springmvc.exception.DBException;
import springmvc.model.CriteriaCustomer;
import springmvc.model.Customer;
@Repository(“customerDAO”)
public class CustomerDAOImpl extends DAO implements CustomerDAO {
@Override
public void save(Customer cust) {
String sql = "INSERT INTO customers(name, address, phone) VALUES(?, ?, ?)";
try {
update(sql, cust.getName(), cust.getAddress(), cust.getPhone());
} catch(SQLException ex){
ex.printStackTrace();
throw new CustomerNameExistException("名字重复了!...");
}
}
@Override
public void delete(Integer id) {
String sql = "DELETE FROM customers WHERE id = ?";
try {
update( sql, id);
} catch(SQLException ex){
ex.printStackTrace();
throw new DBException();
}
}
@Override
public void update(Customer cust) {
String sql = "UPDATE customers SET name = ?, address = ?, phone = ? WHERE id = ?";
try {
update(sql, cust.getName(), cust.getAddress(), cust.getPhone(), cust.getId());
} catch(SQLException ex){
ex.printStackTrace();
throw new DBException();
}
}
@Override
public List<Customer> getForList(CriteriaCustomer cc) {
String sql = "SELECT id, name, address, phone FROM customers " +
"WHERE name LIKE ? AND address LIKE ? AND phone LIKE ?";
try {
return getForList(sql, "%" + cc.getName() + "%",
"%" + cc.getAddress() + "%", "%" + cc.getPhone() + "%");
} catch(SQLException ex){
ex.printStackTrace();
throw new DBException();
}
}
@Override
public Customer getCustomer(Integer id) {
String sql = "SELECT id, name, address, phone FROM customers WHERE id = ?";
try {
return get(sql, id);
} catch(SQLException ex){
ex.printStackTrace();
throw new DBException();
}
}
@Override
public long getCountWithName(String name) {
String sql = "SELECT count(id) FROM customers WHERE name = ?";
try {
return getValue(sql, name);
} catch(SQLException ex){
ex.printStackTrace();
throw new DBException();
}
}
}
CustomerController:
package springmvc.controller;
import java.util.Map;
import javax.annotation.Resource;
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.RequestParam;
import springmvc.dao.CustomerDAO;
import springmvc.model.CriteriaCustomer;
import springmvc.model.Customer;
@Controller(“customer”)
public class CustomerController {
@Resource
private CustomerDAO customerDAO;
@ModelAttribute("customer")
public Customer getCustomer(){
return new Customer();
}
@RequestMapping("/delete")
public String delete(@RequestParam("id") Integer id){
customerDAO.delete(id);
return "redirect:query.action";
}
@RequestMapping("/query")
public String query(CriteriaCustomer cc, Map<String, Object> map){
map.put("customers", customerDAO.getForList(cc));
return "index";
}
@RequestMapping("/toAddCustomer")
public String addCustomer(){
return "addCustomer";
}
@RequestMapping("/saveCustomer")
public String saveCustomer(Customer customer){
customerDAO.save(customer);
return "redirect:query.action";
}
@RequestMapping("/getCustomer")
public String getCustomerForUpdate(@RequestParam("id") Integer id, Map<String, Object> map){
map.put("customer", customerDAO.getCustomer(id));
return "updateCustomer";
}
@RequestMapping("/update")
public String updateCustomer(Customer customer){
customerDAO.update(customer);
return "redirect:query.action";
}
}
CustomerDAOTest:
package springmvc.test;
import java.sql.SQLException;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import springmvc.dao.CustomerDAO;
import springmvc.model.CriteriaCustomer;
import springmvc.model.Customer;
public class CustomerDAOTest {
private CustomerDAO customerDAO = null;
public CustomerDAOTest(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
customerDAO = (CustomerDAO) ctx.getBean("customerDAO");
}
@Test
public void testSave() throws SQLException {
Customer cust = new Customer(null, "XiaoJing", "DaLian", "13920098833");
customerDAO.save(cust);
}
@Test
public void testDelete() throws SQLException {
customerDAO.delete(2);
}
@Test
public void testUpdateCustomer() throws SQLException {
Customer cust = new Customer(3, "XiaoJing3", "DaLian", "13920098833");
customerDAO.update(cust);
}
@Test
public void testGetForListCriteriaCustomer() throws SQLException {
CriteriaCustomer cc = new CriteriaCustomer();
List<Customer> customers = customerDAO.getForList(cc);
System.out.println(customers);
}
@Test
public void testGetCustomer() throws SQLException {
Customer cust = customerDAO.getCustomer(3);
System.out.println(cust);
}
@Test
public void testGetCountWithName(){
long count = customerDAO.getCountWithName("XiaoJing3");
System.out.println(count);
}
}
前台展示的Jsp页面如下:
Index.jsp:
%@page import="java.util.List"%
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding="UTF-8"%>
%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %
Insert title here
<form action="query.action" method="POST">
<table>
<tr>
<td>Name: </td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>Address: </td>
<td>
<input type="text" name="address" />
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
<input type="text" name="phone"/>
</td>
</tr>
<tr>
<td><input type="submit" value="查询全部"/></td>
<td><a href="${baseUrl}/toAddCustomer.action">Create New Customer</a></td>
</tr>
</table>
</form>
<br><br>
<c:if test="${!empty requestScope.customers }">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td>Name:</td>
<td>Address:</td>
<td>Phone:</td>
<td>Update</td>
<td>Delete</td>
</tr>
<c:forEach items="${requestScope.customers }" var="cust">
<tr>
<td>${cust.name }</td>
<td>${cust.address }</td>
<td>${cust.phone }</td>
<td><a href="${baseUrl}/getCustomer.action?id=${cust.id}">UPDATE</a></td>
<td><a href="${baseUrl}/delete.action?id=${cust.id}">DELETE</a></td>
</tr>
</c:forEach>
</table>
</c:if>
<!--
已经执行查询, 但返回的集合中没有任何元素时, 显示: 没有符合条件的员工信息.
-->
<c:if test="${requestScope.customers != null }">
<c:if test="${empty requestScope.customers }">
没有符合条件的员工信息.
</c:if>
</c:if>
addCustomer.jsp:
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding="UTF-8"%>
%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %
Insert title here
<br><br>
<form:form action="saveCustomer.action" method="post"
modelAttribute="customer">
<table>
<tr>
<td>Name: </td>
<td>
<form:input path="name"/>
</td>
</tr>
<tr>
<td>Address: </td>
<td>
<form:input path="address"/>
</td>
</tr>
<tr>
<td>Phone: </td>
<td>
<form:input path="phone"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form:form>
updateCustomer.jsp:
%@page import="java.util.List"%
<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding="UTF-8"%>
%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %
%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %
Insert title here
<c:set value="${requestScope.customer}" var="cust"></c:set>
<form:form action="update.action" method="POST" modelAttribute="customer">
<input type="hidden" name="id" value="${cust.id}">
Name: <input type="text" name="name" value="${cust.name }" /><br>
Address: <input type="text" name="address" value="${cust.address }"/><br>
Phone:<input type="text" name="phone" value="${cust.phone }"/><br>
<input type="submit" value="Update"/>
</form:form>
数据库表结构:
Create Table
CREATE TABLE customers
( ID
int(11) NOT NULL AUTO_INCREMENT, Name
varchar(255) DEFAULT NULL, ADDRESS
varchar(255) DEFAULT NULL, PHONE
varchar(255) DEFAULT NULL,
PRIMARY KEY (ID
)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=gb2312