动态网页项目宠物商店

需要用到的jar包

C3P0连接池 c3p0-0.9.1.2.jar

beanUtils commons-beanutils-1.8.3.jar

dbutils,jdbc的一个集成 commons-dbutils-1.4.jar

logging commons-logging-1.1.1.jar

编写jstl的 jstl.jar

JSP 标准标签库,和jstl.jar 一起使用 standard standard.jar

数据库驱动 mysql-connector-java-8.0.13.jar

1.java

(1)tomcat 服务器的搭建,xml的配置

(2)servlet xml的配置。了解请求和响应

(3)jsp el表达式和jstl的用法

2.mysql

(1)创建数据库

(2)创建表

(3)编写sql语句

3.html

(1)html5的标签

(2)css静态网页的样式

(3)js的一些用法

1.商品查询

需求:有一个页面上面有一个超链接[查询所有商品],点击[查询所有商品],会把数据库中的所有商品信息查询出来,并且展示在表格中

 

如何在一个servlet中判断执行哪个方法:

doGet(request,response){

//获取到method的值

//判断method

if("findAll".equals(method)){

//走查询方法

}else if("add".equals(method)){

//走添加方法

}

}

 

 

//定义查询方法

//定义增加方法

......

 

 

步骤分析:

1.创建数据库和表结构

2.创建动态的web项目,创建包结构,导入项目需要的资源

3.创建一个首页,上面有一个'查询所有商品'的超链接,点击链接后向servlet发送请求    ${pageContext.request.contextPath}/findAll?method=findAll

4.servlet的操作

//获取method

//判断当前method是哪个请求(增删改查)

//编写具体请求的方法

//调用service和dao完成查询数据库所有商品的操作

//返回一个list结合

//把当前的list放入request域对象中

//请求转发到jsp解析

2.增加商品

需求:在首页有个[增加商品]的超链接,点击超链接后,能把用户录入的数据保存到数据库

步骤分析:

1.在首页加一个[添加商品]的超链接 ${pageContext.request.contextPath}/pet?method=addUI

2.点击超链接向servlet发送请求 (请求转发到pet.jsp中  防止pet.jsp直接暴露在地址栏中)

3.用户录入数据后点击增加按钮 向servlet发送请求     

${pageContext.request.contextPath}/pet?method=add(有丢失参数的风险)

  解决方式:<input type="hidden" name="method" value="add">

4.在add方法中

//获取表单中的所有数据  map

//创建pet

//把map中的数据拷贝到pet中

//把pid(UUID)和pdate存放到pet中

//调用service和dao完成数据保存操作

//请求转发到查询所有的链接上   /pet?method=findAll

//如果有异常需要请求转发到error.jsp页面

3.修改商品

需求:点击列表中商品后面的修改按钮,就可以对当前商品信息进行修改,

跳转到修改的表单页面(数据是已经填写好的),在此基础上进行修改,点击修改按钮后,在数据库中更新该条数据

4.删除商品

需求:点击列表中商品后面的删除按钮,点击后,弹出[确认删除该条商品吗?]的提示,点击确认,则删除该条商品,点击取消,不执行删除

5.批量删除商品

需求:根据数据前面的复选框选中情况,批量删除选中的数据

步骤分析:

1.拷贝pet  修改web

2.为表头和列表加上复选框,加上删除勾选的按钮

3.使用jquery实现全选全不选的功能

//导入jquery.js文件

//派发单击事件

//获取表头复选框的选中状态

//获取列表中所有复选框对象

//使列表中复选框状态和表头复选框状态保持一致

4.为列表复选框添加name属性和value  外面嵌套一个form表单  在点击删除勾选的时候派发一个click事件,让事件方法拥有提交form表单的功能

5.servlet的操作

//获取前台传递的id数组

//调用service

6.service操作

//开启事物

//遍历数组

//调用dao删除

//提交事物

//出现异常,回滚事物

7.dao操作

//获取QueryRunner对象

//编写sql

//执行sql(手动获取连接)

6.模糊查询

需求:在列表页面有按照名称和关键字查询的两个输入框,输入查询信息后,点击搜索按钮,那么在下面的列表中会显示出符合条件的数据

select * from pet where pname like ? and pdesc like ?

select * from pet where pname like ?

select * from pet where pdesc like ?

select * from pet

StringBuffer sb = new StringBuffer("select * from where 1=1");

//判断输入的搜索项是否为“”

if(name!=""){

sb.append( and pname like ?)

}

if(kw!=""){

sb.append( and pdesc like ?)

}

首页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
#h{
	margin-top:0px;
	background-color: silver;
	font-style: italic;
	
}
#id1{

	float: left;
}
#id2{
	margin-top:80px;
	float: left;
	
}
#img2{
	margin-top: 80px;
}
</style>
	
</head>
<body background="${pageContext.request.contextPath}/pet/999.jpg">
	

	<h1 id="h" align="center">欢迎来到宠物商店</h1>

	<img width="25px" height="25px" src="${pageContext.request.contextPath}/pet/666.jpg">
	<a id="id1" href="${pageContext.request.contextPath}/pet?method=findAll">
	<input height="100px" type="button" value="查询所有宠物" >
	</a><br>
	<img id="img2" width="25px" height="25px" src="${pageContext.request.contextPath}/pet/666.jpg">
	<a id="id2" href="${pageContext.request.contextPath}/pet?method=UUID">
	<input width: 100px; height="100px" type="button" value="添加新的宠物" >
	</a>
</body>
</html>

list.jsp

<%@ 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>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js"></script>
<style type="text/css">
/*  #pet{
	border:2px solid #000;
	margin:0 auto;
	font-size:13px;
	border-collapse:collapse;
}


#pet tbody tr:nth-child(even)
{
	background-color:#FFC;
}

#pet tbody tr:nth-child(odd)
{
	background-color:#CFF;
}
#pet tbody td:nth-child(2)
{
	width:200px;
	font-weight:bold;
}


#pet tbody tr:hover{
	color:#fff;
	background-color:#F36;
	font-weight:bold;
}
h2{
	font-family: sans-serif;
} */ 
a{font-size: 13px;
	
	}
</style>
</head>
<body background="${pageContext.request.contextPath}/pet/999.jpg">
	<h2 align="center">宠物列表</h2>
	<table border="1px" align="center" id="pet">
	<tr  align="right">
		<td colspan="9" align="center">
			<form action="${pageContext.request.contextPath}/pet" method="post">
			<input type="hidden" name="method" value="search">
			名字:<input type="text" name="name" value="${name}">
			品种:<input type="text" name="kw" value="${kw}">
			<button type="submit">搜索</button>
			<a id="id2" href="${pageContext.request.contextPath}/index.jsp">
			<input width: 100px; height="100px" type="button" value="返回主页" >
			</a>
			</form>
		</td>
		
				
	</tr>
	<tr>
		<th width="4%"><input  type="button" value="删除勾选" id="btn" ><br><input type="checkbox" id="thId"><a>全选</a></th>
		<th width="8%">宠物图片</th>
		<th width="8%">宠物id</th>
		<th width="8%">宠物昵称</th>
		<th width="8%">宠物种类</th>
		<th width="8%">宠物价格</th>
		<th width="8%">到店时间</th>
		<th width="8%">宠物描述</th>
		<th width="8%">操作</th>
	</tr>
	<c:if test="${empty list}">
			<tr>
				<td colspan="9">暂无商品</td>
			</tr>
		</c:if>
		<c:if test="${not empty list}">
			<form id="formId" action="${pageContext.request.contextPath}/pet" method="post">
				<input type="hidden" name="method" value="delCheck">
			<c:forEach items="${list}" var="pet">
				<tr align="center">
					<td><input type="checkbox" name="id" value="${pet.pid}"></td>
					<td height="100px"><img width="100%" height="100%" src="${pageContext.request.contextPath}/${pet.pimage}" /></td>
					<td >${pet.pid}</td>
					<td >${pet.pname}</td>
					<td >${pet.ptype}</td>
					<td >${pet.price}</td>
					<td >${pet.pdate}</td>
					<td >${pet.pdesc}</td>
					<td>
						<a href="${pageContext.request.contextPath}/pet?method=edit&id=${pet.pid}">修改</a>
						<a href="#" onclick="del('${pet.pid}')">删除</a>
					</td>
				</tr>
			</c:forEach>
			</form>
		</c:if>
	</table>
</body>
<script type="text/javascript">
	function del(id){
		var flag = confirm("您确认要删除吗?");
		//根据返回值判断是否删除
		if(flag){
			//执行删除操作
			location.href = "${pageContext.request.contextPath}/pet?method=delete&id="+id;
		}
	}
	//实现全选全不选
	$("#thId").click(function(){
		//获取表头复选框选中状态
		//$("#thId").prop("checked");
		//使列表中复选框选中状态和表头一致
		$("[name=id]").prop("checked",$("#thId").prop("checked"));
	})
	
	//给按钮派发单击事件,提交表单
	$("#btn").click(function(){
		//获取表单
		$("#formId").submit();
	})
</script>
</html>

添加的界面pet.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	 form {
	  height:800px;
      width:300px;
      line-height:30px;
     
      }
      dd {
      margin-left:0;
      }
     #dt1{
     float: left;
     }
	a{
		
		margin-left: 100px;
	}
</style>
</head>
<body background="${pageContext.request.contextPath}/pet/999.jpg">
	<form action="${pageContext.request.contextPath}/pet" method="post">
	<input type="hidden" name="method" value="add">
    <fieldset>
        <legend>添加宠物</legend>
        <dl>
            <dt><label >昵称</label></dt>
            <dd><input type="text" placeholder="请输入昵称" name="pname"/> </dd>
            <dt><label >种类</label></dt>
            <dd><input type="text" placeholder="请输入种类" name="ptype" /></dd>
           	<dt><label>价格</label></dt>
           	<dd><input type="text" placeholder="请输入价格" name="price"></dd>
           	<dt><label>图片</label></dt>
           	<dd><input type="text" placeholder="请输入以.jpg结尾的文件" name="pimage"></dd>
           	<dt><label>宠物描述</label></dt>
           	<dd><textarea rows="5" cols="30" name="pdesc"></textarea><br></dd>
            <dt id="dt1"><button type="submit"/>添加</dt>
            
            <a  id="id2" href="${pageContext.request.contextPath}/index.jsp">
			<input  height="100px" type="button" value="取消" >
			</a>
        </dl>
    </fieldset>
</form>
	
</body>
</html>

修改的界面edit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
	 form {
	  height:800px;
      width:300px;
      line-height:30px;
     
      }
      dd {
      margin-left:0;
      }
	
</style>
</head>
<body background="${pageContext.request.contextPath}/pet/999.jpg">
	<form action="${pageContext.request.contextPath}/pet" method="post">
	<input type="hidden" name="method" value="update">
	<input type="hidden" name="pid" value="${pet.pid}">
    <fieldset>
        <legend>修改宠物</legend>
        <dl>
            <dt><label >昵称</label></dt>
            <dd><input type="text" name="pname" value="${pet.pname}"/></dd>
            <dt><label >种类</label></dt>
            <dd><input type="text" placeholder="请输入种类" name="ptype" value="${pet.ptype}" /></dd>
           	<dt><label>价格</label></dt>
           	<dd><input type="text" placeholder="请输入价格" name="price" value="${pet.price}"/></dd>
           	<dt><label>图片</label></dt>
           	<dd><input type="text" placeholder="请输入以.jpg结尾的文件" name="pimage" value="${pet.pimage}"></dd>
           	<dt><label>宠物描述</label></dt>
           	<dd><textarea rows="5" cols="30" name="pdesc">${pet.pdesc}</textarea><br></dd>
            <dt><button type="submit"/>确认修改</dt>
        </dl>
    </fieldset>
</form>
</body>
</html>

显示错误消息的界面err.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body background="${pageContext.request.contextPath}/pet/999.jpg">
	
		<h1>${msg}</h1>
	
</body>
</html>

java的生成随机id的类

package com.it.servlet;

import java.util.UUID;
//生成随机uid类
public class UUIDCLS {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UUID randomUUID = UUID.randomUUID();
		System.out.println(randomUUID.toString().replace("-", "").toUpperCase().substring(0, 2));
	}
	
	public static String Uid() {
		UUID randomUUID = UUID.randomUUID();
		return randomUUID.toString().replace("-", "").toUpperCase().substring(0, 2);
	}
}

java的servlet

package com.it.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.DbUtils;

import com.it.bean.PetBean;
import com.it.service.PetSevice;

public class PetServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String method = request.getParameter("method");
		if ("findAll".equals(method)) {
			findAll(request,response);
		}else if ("UUID".equals(method)) {
			UUID(request,response);
		}else if ("add".equals(method)) {
			add(request,response);
		}else if ("edit".equals(method)) {
			edit(request,response);
		}else if ("update".equals(method)) {
			update(request,response);
		}else if ("delete".equals(method)) {
			delete(request,response);
		}else if ("delCheck".equals(method)) {
			delCheck(request,response);
		}else if ("search".equals(method)) {
			search(request,response);
		}
	}
	/**
	 * 模糊查询
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//获取前台数据
			String name = request.getParameter("name");
			String kw = request.getParameter("kw");
			//调用service
			PetSevice ps=new PetSevice();
			List<PetBean>list= ps.search(name,kw);
			//放到域中
			for (PetBean petBean : list) {
				System.out.println(petBean.getPname());
			}
			request.setAttribute("list", list);
			request.setAttribute("name", name);
			request.setAttribute("kw",kw);
			//请求转发到list.jsp(因为放入的是list,可以直接解析)
			request.getRequestDispatcher("/list.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "查询失败");
			request.getRequestDispatcher("/err.jsp").forward(request, response);
		} 
	}
	/**
	 *批量删除 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void delCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String[] ids = request.getParameterValues("id");
			//调用service
			PetSevice ps=new PetSevice();
			ps.delCheck(ids);
			//请求转发到查询所有的连接上
			request.getRequestDispatcher("/pet?method=findAll").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "删除多条信息失败");
			request.getRequestDispatcher("/err.jsp").forward(request, response);
		}
	}
	/**
	 * 删除
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String id = request.getParameter("id");
			//调用service执行删除
			PetSevice ps=new PetSevice();
			ps.delete(id);
			//请求转发到查询所有的连接上
			request.getRequestDispatcher("/pet?method=findAll").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "删除宠物信息失败");
			request.getRequestDispatcher("/err.jsp").forward(request, response);
		} 
	}
	/**
	 *修改宠物信息 
	 * @param request
	 * @param response
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) {
		try {
			//获取前台map数据
			Map<String, String[]> map = request.getParameterMap();
			//创建bean,把前台的数据拷贝进去
			PetBean pb=new PetBean();
			BeanUtils.populate(pb, map);
			//调用service更新数据
			PetSevice ps=new PetSevice();
			ps.update(pb);
			//请求转发到findAll上
			request.getRequestDispatcher("/pet?method=findAll").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "修改宠物信息失败");
			request.getRequestDispatcher("err.jsp");
		} 
		
	}
	/**
	 *根据id获取宠物信息,把宠物信息放入域中,请求转发到修改界面(edit.jsp)
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//获取前台id
			String id = request.getParameter("id");
			//调用service根据id查找宠物
			PetSevice ps=new PetSevice();
			PetBean pb= ps.findId(id);
			
			//把pb放入域中并且请求转发到edit.jsp
			request.setAttribute("pet", pb);
			//请求转发到edit.jsp
			request.getRequestDispatcher("/edit.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "查询单条数据失败");
			request.getRequestDispatcher("/err.jsp").forward(request, response);
		}
	}
	/**
	 * 添加宠物
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//获取前台数据
			Map<String, String[]> map = request.getParameterMap();
			//创建bean
			PetBean pb=new PetBean();
			//把map中的数据拷贝到bean中
			BeanUtils.populate(pb, map);
			//把pid和date放入pb中
			pb.setPid(UUIDCLS.Uid());
			pb.setPdate(new Date().toLocaleString());
			//调用service保存数据
			PetSevice ps=new PetSevice();
			ps.add(pb);
			//请求转发到findAll
			request.getRequestDispatcher("/pet?method=findAll").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "添加失败");
			request.getRequestDispatcher("/err.jsp").forward(request, response);
		} 
	}
	//防止资源暴露在外面
	private void UUID(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.getRequestDispatcher("/pet.jsp").forward(request, response);
	}
	/**
	 * 查找所有的宠物
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//创建service
			PetSevice ps = new PetSevice();
			List<PetBean> list= ps.findAll();
			//把list放入域中
			request.setAttribute("list", list);
			//请求转发到list.jsp
			request.getRequestDispatcher("/list.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "查询所有宠物失败");
			request.getRequestDispatcher("/err.jsp").forward(request, response);
		} 
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

service层

package com.it.service;

import java.sql.SQLException;
import java.util.List;

import com.it.bean.PetBean;
import com.it.dao.PetDao;
import com.it.utils.DataSourceUtils;

public class PetSevice {
	/**
	 * 查询所有宠物
	 * @return
	 * @throws SQLException 
	 */
	public List<PetBean> findAll() throws SQLException {
		PetDao pd = new PetDao(); 
			
		return pd.findAll();
	}
	/**
	 * 添加宠物
	 * @param pb
	 * @throws SQLException 
	 */
	public void add(PetBean pb) throws SQLException {
		// TODO Auto-generated method stub
		PetDao pd=new PetDao();
		pd.add(pb);
	}
	/**
	 * 根据id查找宠物
	 * @param id
	 * @return
	 * @throws SQLException 
	 */
	public PetBean findId(String id) throws SQLException {
		PetDao pb=new PetDao();
		return pb.findId(id);
	}
	/**
	 * 修改宠物信息
	 * @param pb
	 * @throws SQLException 
	 */
	public void update(PetBean pb) throws SQLException {
		// TODO Auto-generated method stub
		PetDao pd=new PetDao();
		pd.update(pb);
	}
	/**
	 * 删除
	 * @param id
	 * @throws SQLException 
	 */
	public void delete(String id) throws SQLException {
		PetDao pd=new PetDao();
		pd.delete(id);
		
	}
	/**
	 * 批量删除
	 * @param ids
	 * @throws SQLException 
	 */
	public void delCheck(String[] ids) throws SQLException {
		try {
			//开启事务
			DataSourceUtils.beginTransaction();
			PetDao pd=new PetDao();
			if (ids!=null) {
				for (String id : ids) {
					pd.delCheck(id);
				}
			}
			//提交事务
			DataSourceUtils.commitAndClose();
		} catch (SQLException e) {
			e.printStackTrace();
			DataSourceUtils.rollbackAndClose();
			throw e;
		}
		
	}
	//模糊查询
	public List<PetBean> search(String name, String kw) throws SQLException {
		//调用dao
		PetDao pd=new PetDao();
		
		return pd.sreach(name,kw);
	}
	

	
	
}

dao层

package com.it.dao;

import java.sql.SQLException;
import java.util.ArrayList;
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 com.it.bean.PetBean;
import com.it.utils.DataSourceUtils;

public class PetDao {
	//查询所有宠物
	public List<PetBean> findAll() throws SQLException {
		QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
		String sql="select * from pet";
		List<PetBean> list = qr.query(sql, new BeanListHandler<PetBean>(PetBean.class));
	
		return list;
	}
	//添加宠物
	public void add(PetBean pb) throws SQLException {
		// TODO Auto-generated method stub
		QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
		String sql="insert into pet values (?,?,?,?,?,?,?)";
		qr.update(sql, pb.getPid(),pb.getPname(),pb.getPtype(),pb.getPrice(),"pet/"+pb.getPimage(),pb.getPdate(),pb.getPdesc());
	}
	//根据id查找宠物
	public PetBean findId(String id) throws SQLException {
		QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
		String sql="select * from pet where pid=?";
		PetBean pb = qr.query(sql, new BeanHandler<PetBean>(PetBean.class), id);
		
		return pb;
	}
	//修改宠物信息
	public void update(PetBean pb) throws SQLException {
		QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
		String sql="update pet set pname=?,ptype=?,price=?,pimage=?,pdesc=? where pid=?";
		qr.update(sql, pb.getPname(),pb.getPtype(),pb.getPrice(),pb.getPimage(),pb.getPdesc(),pb.getPid());
	}
	//删除宠物
	public void delete(String id) throws SQLException {
		QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
		String sql="delete from pet where pid=?";
		qr.update(sql,id);
		
	}
	//批量删除
	public void delCheck(String id) throws SQLException {
		// TODO Auto-generated method stub
		QueryRunner qr=new QueryRunner();
		String sql="delete from pet where pid=?";
		//手动获取连接
		qr.update(DataSourceUtils.getConnection(), sql,id);
	}
	public List<PetBean> sreach(String name, String kw) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
		
		StringBuilder sb = new StringBuilder("select * from pet where 1=1");
		List<String> list  = new ArrayList<>();
		System.out.println(name+kw);
		if(name!=""){
			sb.append(" and pname like ?");
			list.add("%"+name+"%");
		}
		
		if(kw!=""){
			sb.append(" and ptype like ?");
			list.add("%"+kw+"%");
		}
		
		List<PetBean> query = qr.query(sb.toString(), new BeanListHandler<PetBean>(PetBean.class), list.toArray());
		return query;
	}
	
	

}

javabean

package com.it.bean;

public class PetBean {
//	`pid` VARCHAR (96),
//	`pname` VARCHAR (150),
//	`ptype` VARCHAR (150),
//	`price` DOUBLE ,
//	`pimage` VARCHAR (600),
//	`pdate` DATE ,
//	`pdesc` VARCHAR (765)
	private String pid;
	private String pname;
	private String ptype;
	private double price;
	private String pimage;
	private String pdate;
	private String pdesc;
	public String getPid() {
		return pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public String getPtype() {
		return ptype;
	}
	public void setPtype(String ptype) {
		this.ptype = ptype;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getPimage() {
		return pimage;
	}
	public void setPimage(String pimage) {
		this.pimage = pimage;
	}
	public String getPdate() {
		return pdate;
	}
	public void setPdate(String pdate) {
		this.pdate = pdate;
	}
	public String getPdesc() {
		return pdesc;
	}
	public void setPdesc(String pdesc) {
		this.pdesc = pdesc;
	}
	
	
	
}

数据库工具类

package com.it.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
	private static DataSource ds=new ComboPooledDataSource();
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	
	//获取连接池
	public static DataSource getDataSource(){
		return ds;
	}
	
	/**
	 * 从当前线程中获取连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException{
		Connection conn = tl.get();
		//若是第一次获取 是null
		if(conn	== null){
			conn=ds.getConnection();
			
			//将这个连接和当前线程绑定
			tl.set(conn);
		}
		
		return conn;
	}
	
	/**
	 *	开启事务
	 * @throws SQLException 
	 */
	public static void beginTransaction() throws SQLException{
		//获取连接
		Connection conn = getConnection();
		
		//开启事务
		conn.setAutoCommit(false);
	}
	
	
	/**
	 * 提交事务且释放资源
	 */
	public static void commitAndClose(){
		try {
			//获取连接
			Connection conn = getConnection();
			
			//提交事务
			if(conn != null){
				conn.commit();
			}
			
			closeConn(conn);
		} catch(Exception e){
			
		}
		
	}
	
	/**
	 * 回滚事务且释放资源
	 */
	public static void rollbackAndClose(){
		try {
			//获取连接
			Connection conn = getConnection();
			
			//回滚事务
			if(conn != null){
				conn.rollback();
			}
			
			closeConn(conn);
			
		} catch (SQLException e) {
			//
		}
	}
	
	/**
	 * 释放资源 且和当前线程解绑
	 * @param conn
	 */
	public static void  closeConn(Connection conn){
		try {
			//释放资源
			if(conn != null){
				conn.close();
			}
			//将线程和连接解绑
			tl.remove();
		} catch (Exception e) {
		}
		
		conn = null;
	}

	
}

servlet配置文件

<?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" 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">
  <display-name>PetStore</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>PetServlet</display-name>
    <servlet-name>PetServlet</servlet-name>
    <servlet-class>com.it.servlet.PetServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PetServlet</servlet-name>
    <url-pattern>/pet</url-pattern>
  </servlet-mapping>
</web-app>

c3p0配置文件

<c3p0-config>
	<!-- 默认配置,如果没有指定则使用这个配置 -->
	<default-config>
		<!-- 基本配置 -->
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/pet</property>
		<property name="user">root</property>
		<property name="password">123</property>
	
		<!--扩展配置-->
		<property name="checkoutTimeout">30000</property>
		<property name="idleConnectionTestPeriod">30</property>
		<property name="initialPoolSize">10</property>
		<property name="maxIdleTime">30</property>
		<property name="maxPoolSize">100</property>
		<property name="minPoolSize">10</property>
		<property name="maxStatements">200</property>
	</default-config> 
	<!-- 命名的配置 -->
	<named-config name="itcast">
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/day17</property>
		<property name="user">root</property>
		<property name="password">1234</property>
		
		
		<!-- 如果池中数据连接不够时一次增长多少个 -->
		<property name="acquireIncrement">5</property>
		<property name="initialPoolSize">20</property>
		<property name="minPoolSize">10</property>
		<property name="maxPoolSize">40</property>
		<property name="maxStatements">20</property>
		<property name="maxStatementsPerConnection">5</property>
	</named-config>
</c3p0-config> 

 

相关文章: