index.jsp
<%@page import="com.greatest.mvcapp.domain.Customer"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var content = $(this).parent().parent().find("td:eq(1)").text();
var flag = confirm("确定要是删除" + content + "的信息吗?");
return flag;
});
});
</script>
</head>
<body>
<form action="query.do" method="post">
<table>
<tr>
<td>CustomerName:</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="Query"/></td>
<td><a href="newcustomer.jsp">Add New Customer</a></td>
</tr>
</table>
</form>
<br><br>
<%
List<Customer> customers = (List<Customer>)request.getAttribute("customers");
if(customers != null && customers.size() > 0){
%>
<hr>
<br><br>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>CustomerName</th>
<th>Address</th>
<th>Phone</th>
<th>UPDATE\DELETE</th>
</tr>
<%
for(Customer customer: customers){
%>
<tr>
<td><%= customer.getId() %></td>
<td><%= customer.getName() %></td>
<td><%= customer.getAddress() %></td>
<td><%= customer.getPhone() %></td>
<td>
<a href="edit.do?id=<%= customer.getId() %>">UPDATE</a>
<a href="delete.do?id=<%= customer.getId() %>" class="delete">DELETE</a>
</td>
</tr>
<%
}
%>
</table>
<%
}
%>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<h4>操作成功!!</h4>
<h4><a href="query.do">Return...</a></h4>
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<h4>对不起,没有您请求的页面</h4>
</body>
</html>
updatecustomer.jsp
<%@page import="com.greatest.mvcapp.domain.Customer"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<%---1.页面出现 显示要修改的那个人的值
2.同修改的 newcustomer.jsp,显示 用户名被占用 。 name是旧的值 address,phone是新的的值 --%>
<c:if test="${requestScope.message !=null }"></c:if>
<br>
<font color="red">${requestScope.message }</font>
<br>
<br>
<c:set var="id" value="${customer !=null ? customer.id : param.id }"></c:set>
<c:set var="oldName" value="${customer !=null ? customer.name : param.oldName }"></c:set>
<c:set var="name" value="${customer !=null ? customer.name : param.oldName }"></c:set>
<c:set var="address" value="${customer !=null ? customer.address : param.address }"></c:set>
<c:set var="phone" value="${customer !=null ? customer.phone : param.phone }"></c:set>
<form action="update.do" method="post">
<input type="hidden" name="id" value="${id }"/>
<input type="hidden" name="oldName" value="${oldName }"/>
<table>
<tr>
<td>CustomerName:</td>
<td><input type="text" name="name" value="${name }"></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address" value="${address }"></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="phone" value="${phone }"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>
newcustomer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<%
Object msg=request.getAttribute("message");
if(msg!=null){ %>
<br>
<font color="red"><%=msg %></font>
<br>
<br>
<%
}
%>
<form action="addCustomer.do" method="post">
<table>
<tr>
<td>CustomerName:</td>
<td><input type="text" name="name" value="<%= request.getParameter("name")==null ? "":request.getParameter("name")%>"></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address" value="<%= request.getParameter("address")==null ? "":request.getParameter("address")%>"></td>
</tr>
<tr>
<td>Phone</td>
<td><input type="text" name="phone" value="<%= request.getParameter("phone")==null ? "":request.getParameter("phone")%>"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>
package com.greatest.customerdaoFactory;
import java.util.HashMap;
import java.util.Map;
import com.greatest.mvcapp.dao.Customerdao;
import com.greatest.mvcapp.dao.imp.CusromerDAOjdbcimp;
import com.greatest.mvcapp.dao.imp.CustomerDAOXMLimp;
public class customerdaofactory {
//工厂一般都是单例 的
private customerdaofactory(){
dao.put("jdbc",new CusromerDAOjdbcimp());
dao.put("xml", new CustomerDAOXMLimp());
}
//map接收
private Map<String ,Customerdao> dao=new HashMap<String ,Customerdao>();
//单例模式
private static customerdaofactory instance=new customerdaofactory();
public static customerdaofactory getinstance(){
return instance;
}
private String type=null;
//根据init方法返回的键确定值
public void settype(String type){
this.type=type;
}
//返回结果给方法的调用者
public Customerdao getCustomerdao(){
return dao.get(type);
}
}
package com.greatest.CustromerServlet;
public class CriteriaCustomer {
private String name;
private String address;
private String phone;
/**
* @return the name
*/
public String getName() {
if (name == null) {
name = "%%";
} else {
name = "%" + name + "%";
}
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the address
*/
public String getAddress() {
if (address == null) {
address = "%%";
} else {
address = "%" + address + "%";
}
return address;
}
/**
* @param address
* the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return the phone
*/
public String getPhone() {
if (phone == null) {
phone = "%%";
} else {
phone = "%" + phone + "%";
}
return phone;
}
/**
* @param phone
* the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
public CriteriaCustomer(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
this.phone = phone;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "CriteriaCustomer [name=" + name + ", address=" + address + ", phone=" + phone + "]";
}
}
package com.greatest.CustromerServlet;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.greatest.customerdaoFactory.customerdaofactory;
import com.greatest.mvcapp.dao.Customerdao;
import com.greatest.mvcapp.dao.imp.CusromerDAOjdbcimp;
import com.greatest.mvcapp.dao.imp.CustomerDAOXMLimp;
import com.greatest.mvcapp.domain.Customer;
/**
* Servlet implementation class customerservlet
*/
@WebServlet("*.do")
public class customerservlet extends HttpServlet {
// private Customerdao customerdao=new CusromerDAOjdbcimp();
private Customerdao customerdao = customerdaofactory.getinstance().getCustomerdao();
private static final long serialVersionUID = 1L;
/**
* s
*
* @see HttpServlet#doGet1(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
// protected void doPost(HttpServletRequest request, HttpServletResponse
// response) throws ServletException, IOException {
// String method=request.getParameter("method");
//
//
// //添加:customerServlet?method=add
//
// switch(method){
// case "add":add(request,response);break;
// case "query":query(request,response);break;
// case "delete":delete(request,response);break;
// case "update":update(request,response);break;
//
// }
//
//
// // TODO Auto-generated method stub
// doGet(request, response);
// }
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("1");
// 1.获取ServletPath:映射路径 /edit.do或 /addCustomer.do
String servletp = req.getServletPath();
// String s = str.substring(begin);
// s 为 str 从begin位置到最后的字符串
// String s = str.substring(begin,end)
// s 是 str 从begin 位置到end 位置的字符串
// 2.去除/和 .do 得到类似于 edit或 addCustomer这样的字符
System.out.println(servletp);
String methodname = servletp.substring(1);
methodname = methodname.substring(0, methodname.length() - 3);
try {
// 3.利用反射 获取methodname对应的方法 一以下
Method method = getClass().getDeclaredMethod(methodname, HttpServletRequest.class,
HttpServletResponse.class);
// 4. 利用反射调用对应的方法
method.invoke(this, req, res);
} catch (Exception e) {
e.printStackTrace();
// 可以有一些响应
// res.sendRedirect("error.jsp");
}
}
private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String forwardPath = "/error.jsp";
// 1 获取请求参数 id 根据id显示信息
String idstr = request.getParameter("id");
// 2.调用Customerdao的customerdao.get(id)获取和id对应的Customer的对象customer
// 信息放入页面中
try {
Customer customer = customerdao.get(Integer.parseInt(idstr));
if (customer != null) {
forwardPath = "/updatecustomer.jsp";
// 3.将customer放入request中
request.setAttribute("customer", customer);
}
} catch (Exception e) {
}
// 响应updatedcustomer.jsp页面 --》jsp页面
request.getRequestDispatcher(forwardPath).forward(request, response);
}
private void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 1.获取表单参数 id name address phone oldName
String id = request.getParameter("id");
String name = request.getParameter("name");
String address = request.getParameter("address");
String phone = request.getParameter("phone");
String oldName = request.getParameter("oldName");
// 2.检验name是否被占用:
// 2.1 比较name和oldName是否相同 若相同说明可用
// 2.1若不相同 则调用Customerdao的getCountWithName(String name) 获取name在数据库中是否存在
if (!oldName.equalsIgnoreCase(name)) {//如果老名字和新名字不同
long count = customerdao.getCountWithName(name);
// 2.2若返回值大于0则相应uodatecustomer.jsp页面 :通过转法方式来响应newcustomer.jsp页面
if (count > 0) {
// 2.2.1在updatecustomer.jsp页面显示一个错误消息
// 用户名已经被占用请重新选择
// 在request中放一个属性message: 用户名已经被占用请重新选择
// 在页面上通过 request。getAttribute()方式显示
request.setAttribute("message", "用户名" + name + "已经被占用,请重新选择");
// 2.2.2newcsutomer.jsp的表单值可以回显
// address,phone显示新的值name显示的是oldName的值
// 2.2.3解暑方法 rreturn
request.getRequestDispatcher("/updatecustomer.jsp").forward(request, response);
return;
}
}
// 3.若通过验证 则把表单参数封装为一个Customer对象
// customer
Customer customer = new Customer(name, address, phone);
customer.setId(Integer.parseInt(id));
// 调用customerdao的update方法执行跟新操作
customerdao.update(customer);
// 从定向 到query。do
response.sendRedirect("query.do");
}
private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 获取id 调用DAO 的delete方法 进行删除
String idstr = request.getParameter("id");
int id = 0;
// try catch 的作用 防止instr不能转为int类型 ?id=abc
// 若不能 转则id=0 ,无法进行任何的删除操作
try {
// integer.parseint()将字符串型的数字转换为整型的数字
id = Integer.parseInt(idstr);
customerdao.delete(id);
response.sendRedirect("query.do");
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
private void query(HttpServletRequest request, HttpServletResponse response) throws Exception, Exception {
// 1.获取模糊查询的请求参数
String name = request.getParameter("name");
String address = request.getParameter("address");
String phone = request.getParameter("phone");
// 把请求封装为一个CriteriaCustomer对象
CriteriaCustomer cc = new CriteriaCustomer(name, address, phone);
// 1.调用CustomerDAO的 getForListWithCriteriaCustomer()得到Customer的集合
List<Customer> customers = customerdao.getForListWithCriteriaCustomer(cc);
// 2.把Customer集合放入request中
request.setAttribute("customers", customers);
// 3.转发页面到inde.jsp(不能使用从定向)
request.getRequestDispatcher("/index.jsp").forward(request, response);
System.out.println("2");
// //1. 调用 CustomerDAO 的 getAll() 得到 Customer 的集合
// List<Customer> customers = customerdao.getAll();
// //2. 把 Customer 的集合放入 request 中
// request.setAttribute("customers", customers);
// //3. 转发页面到 index.jsp(不能使用重定向)
// request.getRequestDispatcher("/index.jsp").forward(request,
// response);
}
private void addCustomer(HttpServletRequest request, HttpServletResponse response) throws Exception, IOException {
// 1 获取表单参数 :name.address. phone
String name = request.getParameter("name");
String address = request.getParameter("address");
String phone = request.getParameter("phone");
// 2.检验name是否被占用
// 2.1 调用 Customerdao的getCountWithName(String name )获取name在数据苦衷是否存在
long count = customerdao.getCountWithName(name);
// 2.2若返回值大于0 说明 被占用 返回newcustomer.jsp页面
// 通过转发的方式来响应newcustomer.jsp页面
if (count > 0) {
// 2.2.1要求在newcustomer.jsp页面上显示一个错误消息
// :用户名name已经被占用,请重新选择
// 在request中放入一个属性message:用户名name已经被占用,请重新选择
// 在页面通过request。getAttribute("message")的方式来显示
request.setAttribute("message", "用户名" + name + "已经被占用,请重新选择");
// 2.2.2 newcustomer.jsp的表单值可以回显
// 通过value<%= request.getParamener(name)==null ?
// "":request.get[Parameter("name")%>来进行回显
// 2.2.3结束方法:return
System.out.println("3");
request.getRequestDispatcher("/newcustomer.jsp").forward(request, response);
return;
}
// 3.若通过验证,则把表单参数风装为一个Customer的对象customer
Customer customer = new Customer(name, address, phone);
// 4. 调用 Customerdao的save(Custoemr customer)方法 执行保存操作
customerdao.save(customer);
// 5.重定向到succeess.jsp页面 ;使用重定向可以避免表但的重复提交
response.sendRedirect("success.jsp");
// request.getRequestDispatcher("/success.jsp").forward(request,
// response);
}
}
package com.greatest.CustromerServlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import com.greatest.customerdaoFactory.customerdaofactory;
public class initServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
customerdaofactory.getinstance().settype("jdbc");
//读取类路径下的switch.properties文件
InputStream in=getServletContext().getResourceAsStream("/WEB-INF/classes/switch.properties");
Properties p=new Properties();
try {
p.load(in);
//获取switch.properties的type属性值
String type=p.getProperty("type");
//赋给了Custpomerdaofactory的type属性值
customerdaofactory.getinstance().settype(type);
System.out.println(type);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.greatest.mvcapp.dao;
import java.util.List;
import com.greatest.CustromerServlet.CriteriaCustomer;
import com.greatest.mvcapp.domain.Customer;
public interface Customerdao {
public List<Customer> getAll();
public void save(Customer customer);
public Customer get(Integer id);
public void delete(Integer id);
public void update(Customer customer);
public long getCountWithName(String name);
public List<Customer> getForListWithCriteriaCustomer(CriteriaCustomer cc);
}
package com.greatest.mvcapp.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.greatest.CustromerServlet.CriteriaCustomer;
import com.greatest.mvcapp.db.jdbcUtils;
import com.greatest.mvcapp.domain.Customer;
public class DAO<T> {
/*
* 封装了基本的CRUD方法,以供子类继承使用 当前Dao直接在方法中获取数据库链接 整个DAO采取DButils解决方案 , <T> 当前DAO
* 处理的实体类的类型是什么 query方法返回值,返回的是T 泛型, 具体返回值类型,跟随结果集处理方式变化
*/
private QueryRunner queryRunner = new QueryRunner();
// 确定clazz
private Class<T> clazz;
public DAO() {
// 先获取带泛型的父类
Type superClass = getClass().getGenericSuperclass();
// 如果他确实是带参数的话
if (superClass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) superClass;
// 获取参数
Type[] typeArgs = parameterizedType.getActualTypeArguments();
// 如果有参数的话 获取第一个 第一个强转为Class类 并给clazz实例赋值customer
if (typeArgs != null && typeArgs.length > 0) {
if (typeArgs[0] instanceof Class) {
clazz = (Class<T>) typeArgs[0];
}
}
}
}
/*
* 返回某一个字段的值:例如返回某一条记录的customerName,或返回数据表中有多少条记录等;
*/
public <E> E getForValue(String sql, Object... args) {
Connection con = null;
try {
con = jdbcUtils.getConnection();
return (E) queryRunner.query(con, sql, new ScalarHandler(), args);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
* 返回T所对应的List
*/
public List<T> getForList(String sql, Object... args) {
Connection con = null;
try {
con = jdbcUtils.getConnection();
return queryRunner.query(con, sql, new BeanListHandler<>(clazz), args);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jdbcUtils.releaseConnection(con);
}
return null;
}
/*
* 返回对应的T的一个实例类的对象
*/
public T get(String sql, Object... args) {
Connection con = null;
try {
con = jdbcUtils.getConnection();
return queryRunner.query(con, sql, new BeanHandler<>(clazz), args);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*
* 该方法封装了 insert delete update 操作 sql sql语句 args 填充sql语句的占位符
*/
public void update(String sql, Object... args) {
Connection con = null;
try {
con = jdbcUtils.getConnection();
queryRunner.update(con, sql, args);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
jdbcUtils.releaseConnection(con);
}
}
}
package com.greatest.mvcapp.dao.imp;
import java.util.List;
import com.greatest.CustromerServlet.CriteriaCustomer;
import com.greatest.mvcapp.dao.Customerdao;
import com.greatest.mvcapp.dao.DAO;
import com.greatest.mvcapp.domain.Customer;
public class CusromerDAOjdbcimp extends DAO<Customer> implements Customerdao {
@Override
// 查询全部
public List<Customer> getAll() {
String sql = "select Id,name,address,phone from customer";
return getForList(sql);
}
// 插入
@Override
public void save(Customer customer) {
// TODO Auto-generated method stub
String sql = "insert into customer(name,address,phone) values(?,?,?)";
update(sql, customer.getName(), customer.getAddress(), customer.getPhone());
}
// 根据id查找信息
@Override
public Customer get(Integer id) {
String sql = "select id,name,address,phone from customer where id=?";
return get(sql, id);
}
// 根据id删除
@Override
public void delete(Integer id) {
// TODO Auto-generated method stub
String sql = "delete from customer where id=?";
update(sql, id);
}
// 根据name查询有几个
@Override
public long getCountWithName(String name) {
String sql = "select count(id) from customer where name=?";
return getForValue(sql, name);
}
// 修改
@Override
public void update(Customer customer) {
// TODO Auto-generated method stub
String sql = "update customer set name=?,address=?,phone=? where id=?";
update(sql, customer.getName(), customer.getAddress(), customer.getPhone(), customer.getId());
}
@Override
public List<Customer> getForListWithCriteriaCustomer(CriteriaCustomer cc) {
String sql = "select id,name,address,phone from customer where name like ? and address like ? and phone like ?";
// 修改了CriteriaCustomer的getter()方法:其返回的字符串有“%%”
// 若其返回值为null;则返回“%%”,若不为null 则返回“%%”+字段本身的值+“%”
return getForList(sql, cc.getName(), cc.getAddress(), cc.getPhone());
}
}
package com.greatest.mvcapp.dao.imp;
import java.util.List;
import com.greatest.CustromerServlet.CriteriaCustomer;
import com.greatest.mvcapp.dao.Customerdao;
import com.greatest.mvcapp.domain.Customer;
public class CustomerDAOXMLimp implements Customerdao {
@Override
public List<Customer> getAll() {
System.out.println("getAll");
return null;
}
@Override
public void save(Customer customer) {
System.out.println("save");
// TODO Auto-generated method stub
}
@Override
public Customer get(Integer id) {
System.out.println("get");
// TODO Auto-generated method stub
return null;
}
@Override
public void delete(Integer id) {
System.out.println("delete");
}
@Override
public void update(Customer customer) {
System.out.println("update");
}
@Override
public long getCountWithName(String name) {
System.out.println("getCountWithName");
return 0;
}
@Override
public List<Customer> getForListWithCriteriaCustomer(CriteriaCustomer cc) {
System.out.println("getForListWithCriteriaCustomer");
return null;
}
}
package com.greatest.mvcapp.db;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class jdbcUtils {
//释放Connection链接
public static void releaseConnection(Connection con) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//如何从数据库连接池中获取链接 让当前private jdbcUtils维护一个连接池
//项目中往往有一个连接池就够了 所以是静态的
private static DataSource d = null;
//数据库连接池植被初始化一次 节省内存
static {
d = new ComboPooledDataSource("helloc3p0");
}
public static Connection getConnection() throws Exception {
return d.getConnection();
}
}
package com.greatest.mvcapp.domain;
public class Customer {
private int Id;
private String name;
private String address;
private String phone;
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Customerdao [Id=" + Id + ", name=" + name + ", address=" + address + ", phone=" + phone + "]";
}
public Customer(int id, String name, String address, String phone) {
super();
Id = id;
this.name = name;
this.address = address;
this.phone = phone;
}
public Customer( String name, String address, String phone) {
super();
this.name = name;
this.address = address;
this.phone = phone;
}
public Customer() {
super();
// TODO Auto-generated constructor stub
}
/**
* @return the id
*/
public int getId() {
return Id;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
Id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the address
*/
public String getAddress() {
return address;
}
/**
* @param address
* the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone
* the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
}
package com.greatest.mvcapp.test;
import java.util.List;
import org.junit.Test;
import com.greatest.CustromerServlet.CriteriaCustomer;
import com.greatest.mvcapp.dao.Customerdao;
import com.greatest.mvcapp.dao.imp.CusromerDAOjdbcimp;
import com.greatest.mvcapp.domain.Customer;
public class CusromerDAOjdbcimptest {
private Customerdao cd = new CusromerDAOjdbcimp();
@Test
public void testGetForListWithCriteriaCustomer(){
CriteriaCustomer cc=new CriteriaCustomer("吕",null,null);
List <Customer> customers=cd.getForListWithCriteriaCustomer(cc);
System.out.println(customers);
}
@Test
public void testGetAll() {
List<Customer> customer = cd.getAll();
System.out.println(customer);
}
@Test
public void testSave() {
Customer cu = new Customer();
cu.setAddress("Shanxi");
cu.setName("an");
cu.setPhone("13700568897");
cd.save(cu);
}
@Test
public void testGetInteger() {
Customer cu1 = cd.get(1);
System.out.println(cu1);
}
@Test
public void testDelete() {
cd.delete(26);
}
@Test
public void testUpdateCustomer() {
long count = cd.getCountWithName("吕谦");
System.out.println(count);
}
}
<c3p0-config>
<named-config name="helloc3p0">
<!-- 指定连接数据源的基本属性 -->
<property name="user">root</property>
<property name="password">root</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///test</property>
<!-- 若数据库中连接数不足时, 一次向数据库服务器申请多少个连接 -->
<property name="acquireIncrement">5</property>
<!-- 初始化数据库连接池时连接的数量 -->
<property name="initialPoolSize">5</property>
<!-- 数据库连接池中的最小的数据库连接数 -->
<property name="minPoolSize">5</property>
<!-- 数据库连接池中的最大的数据库连接数 -->
<property name="maxPoolSize">10</property>
<!-- C3P0 数据库连接池可以维护的 Statement 的个数 -->
<property name="maxStatements">20</property>
<!-- 每个连接同时可以使用的 Statement 对象的个数 -->
<property name="maxStatementsPerConnection">5</property>
</named-config> <!--结束 -->
</c3p0-config>
type=xml
#type=jdbc
c3p0-0.9.1.2.jar
commons-beanutils-1.8.0.jar
mysql-connector-java-5.1.7-bin (1).jar