Spring MVC流程說明: 用戶向Web服務器發送請求 Web服務器根據web.xml文件找到請求映射到的Contorller處理器。 處理器根據請求訪問業務Service層和DAO層進行處理而後把得出的返回結果到前端JSP頁面 用戶經過返回結果獲得相應的信息html
項目配置文件以下: Web.xml:前端
<?xml version="1.0" encoding="UTF-8"?>java
<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> </web-app>mysql
db.properties: user=root password=1204 driver=com.mysql.jdbc.Driver url=jdbc:mysql:///test SpringMVC配置文件:web
<?xml version="1.0" encoding="UTF-8"?>spring
<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> </beans> Spring 配置文件:sql
<?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: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> </beans>spring-mvc
源碼: 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<T>{ 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<Customer> 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" %> <c:set value="${pageContext.request.contextPath }" var="baseUrl"></c:set>緩存
<!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>Insert title here</title> </head> <body>
<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>
</body> </html> addCustomer.jsp: <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ 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>Insert title here</title> </head> <body>
<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>
</body> </html> 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" %>
<!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>Insert title here</title> </head> <body> <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>
</body> </html> 數據庫表結構: 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