dbutils与案例操作

1.tomcat内置连接池管理(了解)
        tomcat内置连接池使用的是dbcp。
        
        问题1:tomcat怎样管理连接池?(配置)
            要想将一个dbcp连接池让 tomcat管理,只需要创建一个context.xml配置文件,在配置文件中
            配置相关信息,
            <Context>
              <Resource name="jdbc/EmployeeDB" auth="Container"
                        type="javax.sql.DataSource" username="root" password="abc"
                        driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql:///day18"
                        maxActive="8" maxIdle="4"/>
            </Context>
            问题:context.xml文件位置:
                1.在tomcat/conf/context.xml     这时这个连接池是给整个服务器使用的。
                2.在tomcat/conf/Catalina/localhost 这时这个连接池只给localhost虚拟主机使用。
                3.将context.xml文件放置在web应用的META-INF下
                
                注意:如果是全局设置,那么我们需要将数据库驱动放置在tomcat/lib目录下

        
        问题2:怎样从tomcat中获取连接池?
            我们在servlet中获取连接池对象。
            Context context = new InitialContext();
            Context envCtx = (Context)context.lookup("java:comp/env"); 固定路径
            DataSource datasource = (DataSource) envCtx.lookup("jdbc/EmployeeDB");
            
        JNDI----->    JNDI(Java Naming and Directory Interface,Java命名和目录接口)是SUN公司提供的一种标准的Java命名系统接口,JNDI提供统一的客户端API,通过不同的访问提供者接口JNDI SPI的实现,由管理者将JNDI API映射为特定的命名服务和目录系统,使得Java应用程序可以和这些命名服务和目录服务之间进行交互。目录服务是一种命名服务,在这种服务里,对象不但有名称,还有属性。
--------------------------------------------------------------------------------------------                    
2.元数据            
    问题:元数据是什么,有什么作用?    
        元数据(metaData)  指数据库中 库、表、列的定义信息
        
        1.DataBaseMetaData 数据库元数据(了解)
            问题:怎样获取一个DataBaseMetaData?
                
                Connection接口中定义了一个方法 getMetaData();
                
            问题:常用API
                
                String driverName = dmd.getDriverName(); //获取驱动名称
                System.out.println(driverName);
                
                String userName = dmd.getUserName();//获取用户名
                System.out.println(userName);
                
                String url = dmd.getURL();//获取url
                System.out.println(url);
                
                String databaseProductName = dmd.getDatabaseProductName(); //获取数据库名称
                System.out.println(databaseProductName);
                
                String databaseProductVersion = dmd.getDatabaseProductVersion();//获取数据库版本.
                System.out.println(databaseProductVersion);
                
                ResultSet getPrimaryKeys(String catalog,
                         String schema,
                         String table)
                         throws SQLException
                获取表中主键相关描述
                    每个主键列描述都有以下列:
                    TABLE_CAT String => 表类别(可为 null)
                    TABLE_SCHEM String => 表模式(可为 null)
                    TABLE_NAME String => 表名称
                    COLUMN_NAME String => 列名称
                    KEY_SEQ short => 主键中的序列号(值 1 表示主键中的第一列,值 2 表示主键中的第二列)。
                    PK_NAME String => 主键的名称(可为 null)
                
            
        2.ParameterMetaData 参数元数据
            参数元数据主要用于获取:sql语句中占位符的相关信息.
            
            问题:怎样获取ParameterMetaData?
                在PreparedStatement中有一个方法getParameterMetaData可以获取.
                
            问题:怎样使用?
                int count = pmd.getParameterCount(); // 获取参数 个数
                System.out.println(count);
                
                String type1 = pmd.getParameterTypeName(1);//获取参数的类型
                System.out.println(type1);
                
                注意:在获取参数类型时会产生异常
                    java.sql.SQLException: Parameter metadata not available for the given statement
                解决方案:
                    在url后添加参数
                    jdbc:mysql:///day18?generateSimpleParameterMetadata=true
                添加这个参数后,我们在获取,它的结果也是varchar,原因:是mysql驱动的支持问题。    
            
        3.ResultSetMetaData 结果集元数据
            
            问题:怎样获取结果集元数据?
                可以通过ResultSet的getMetaData()方法获取.
                
            问题:怎样使用?
                System.out.println(rsmd.getColumnCount());//获取结果集中列数量
        
                System.out.println(rsmd.getColumnName(2));//获取结果集中指定列的名称.
                
                System.out.println(rsmd.getColumnTypeName(3));//获取结果集中指定列的类型。
=============================================================================================================
3.dbutils工具(重要)
    问题:dbutils是什么,有什么作用?
        它就是一个简单的jdbc封装工具.
        使用dbutils可以简化操作.
        要使用dbutils需要导入jar包.
        
    dbutils核心
        1.QueryRunner类
            它是用于执行sql语句的类。
            1.query 用于执行select
            2.update 用于执行update delete insert
            3.batch 批处理
        2.ResultSetHandler接口
            用于定义结果集的封装                
            它提供九个实现类,可以进行不同的封装。
        3.DbUtils类
            它提供关于关闭资源以及事务rollback,commit操作。
    -----------------------------------------------------
    Dbutlis详解
        1.QueryRunner
            1.QueryRunner怎样获取
                1.new QueryRunner()
                    如果是使用这种构造创建的QueryRunner,它的事务是手动控制.
                2.new QueryRunner(DataSource ds);
                    如果是使用这种构造,它的事务是自动事务,简单说,一条sql一个事务。
                
            2.QueryRunner中的三个核心方法
                query
                update
                batch
                对于上述三个方法,它们提供很多重载。
                如果QueryRunner在创建时,没有传递DataSource参数,那么在使用
                query,update,batch方法时,要传递Connection参数
                如果QueryRunner在创建时,传递了Dataource参数,好么在使用
                query,update,batch方法时,不需要传递Connection参数。
                
            总结:
                怎样配套使用:
                    QueryRunner runner=new QueryRunner();
                    runner.query(Connection,sql,ResultSetHandler,Object... param);
                    runner.update(Connection,sql,Object...param);
                    runner.batch(Connection con,sql,Object[][] objs);
                    
                    QueryRunner runner=new QueryRunner(DataSource ds);
                    runner.query(sql,ResultSetHandler,Object... param);
                    runner.update(sql,Object...param);
                    runner.batch(sql,Object[][] objs);
                    
        -----------------------------------------------------------------            
        ResultSetHandler接口    
            用于封装结果集.
            
    ============================================================================
    模仿QueryRunner
        1.query方法模仿
            public <T> T query(Connection con, String sql, MyResultSetHandler<T> mrs,Object... params) throws SQLException {

                    PreparedStatement pst = con.prepareStatement(sql); // 得到一个预处理的Statement.
                    // 问题:sql语句中可能存在参数,需要对参数赋值。

                    ParameterMetaData pmd = pst.getParameterMetaData();
                    // 可以得到有几个参数
                    int count = pmd.getParameterCount();
                    for (int i = 1; i <= count; i++) {
                        pst.setObject(i, params[i - 1]);
                    }

                    ResultSet rs = pst.executeQuery(); // 得到了结果集,要将结果集封装成用户想要的对象,但是,工具不可能知道用户需求。

                    return mrs.handle(rs);
                }
        2.update方法模仿
            public int update(Connection con, String sql, Object... params) throws SQLException {

                PreparedStatement pst = con.prepareStatement(sql); // 得到一个预处理的Statement.
                // 问题:sql语句中可能存在参数,需要对参数赋值。

                ParameterMetaData pmd = pst.getParameterMetaData();
                // 可以得到有几个参数
                int count = pmd.getParameterCount();
                for (int i = 1; i <= count; i++) {
                    pst.setObject(i, params[i - 1]);
                }

                int row = pst.executeUpdate();
                // 关闭资源
                pst.close();
                return row;
            }
===============================================================================    
ResulsetHandler九个实现类
            
             ArrayHandler, 将结果集中第一条记录封装到Object[],数组中的每一个元素就是记录中的字段值。
             ArrayListHandler, 将结果集中每一条记录封装到Object[],数组中的每一个元素就是记录中的字段值。在将这些数组装入到List集合。
            
             BeanHandler(重点), 将结果集中第一条记录封装到一个javaBean中。
             BeanListHandler(重点), 将结果集中每一条记录封装到javaBean中,在将javaBean封装到List集合.
            
             ColumnListHandler, 将结果集中指定列的值封装到List集合.
            
             MapHandler, 将结果集中第一条记录封装到Map集合中,集合的 key就是字段名称,value就是字段值
             MapListHandler, 将结果集中每一条记录封装到Map集合中,集合的 key就是字段名称,value就是字段值,在将这些Map封装到List集合
            
             KeyedHandler,在使用指定的列的值做为一个Map集合的key,值为每一条记录的Map集合封装。
             ScalarHandler 进行单值查询 select count(*) from account;
            
        ---------------------------------------------------------
        扩展:实现BeanHandler
            使用BeanUtils实现
                Object obj = null;

                Map<String, String[]> map = new HashMap<String, String[]>();

                ResultSetMetaData md = rs.getMetaData();
                int count = md.getColumnCount();

                if (rs.next()) {
                    try {
                        obj = clazz.newInstance();
                        for (int i = 1; i <= count; i++) {
                            map.put(md.getColumnName(i),
                                    new String[] { rs.getString(md.getColumnName(i)) });
                        }
                        BeanUtils.populate(obj, map);
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }

                }

                return obj;
        
---------------------------------------------------    
----------------------------------------------------

案例操作

    登录成功后,访问到一个页面success.jsp,在页面上添加一个连接
    
    就是客户信息的CRUD操作.
    

    1.客户信息

    
        字段名    说明    类型
        Id    编号    varchar(40)
        name    客户姓名    varchar(20)
        gender    性别    varchar(10)
        birthday    生日    date
        cellphone    手机    varchar(20)
        email    电子邮件    varchar(40)
        preference    客户爱好    varchar(100)
        type    客户类型    varchar(40)
        description    备注    varchar(255)

        create table customer(
           id varchar(40) primary key,
           name varchar(20),
           gender varchar(10),
           birthday date,
           cellphone varchar(20),
           email varchar(40),
           preference varchar(100),
           type varchar(40),
           description varchar(255)
        );

2.搭建环境

        JavaEE 三层结构
        Servlet + JSP + JavaBean+jstl + DBUtils+ DAO + MySQL

        导入jar包 :JSTL 、BeanUtils、DBUtils、C3P0、mysql驱动

        创建包结构
        cn.itcast.customer.web  表现层
        cn.itcast.customer.service 业务层
        cn.itcast.customer.dao 持久层
        cn.itcast.customer.utils 工具包
        cn.itcast.customer.domain 实体类  javaBean


        应用的jar文件
        1.    mysql驱动包
        2.    c3po包
        3.    dbutils包
        4.    BeanUtil包
        5.    JSTL包
        6.    c3p0的配置文件
        
    ------------------------------------------------------
    编写代码:
        1.创建Customer这个javaBean
            private String id;
            private String name;
            private String gender;
            private Date birthday;
            private String cellphone;
            private String email;
            private String preference;
            private String type;
            private String description;
            
        2.为了测试方便,向customer表中插入数据
            insert into customer values("a11","tom","男","2010-10-10","13888888888","tom@163.com","吃,喝,玩","vip","good man");
            insert into customer values("a11","fox","男","2000-10-10","13888888888","tom@163.com","吃,喝,玩","vip","good man");
            insert into customer values("a11","james","男","1990-10-10","13888888888","tom@163.com","吃,喝,玩","vip","good man");
            
            

3.实现查询所有客户信息操作

            1.在success.jsp页面添加连接
                <a href="${pageContext.request.contextPath}/findAll">查看所有客户信息</a>
            2.在CustomerFindAllServlet中调用service,在service中调用dao,最后得到一个List<Customer>.

            3.在showCustomer.jsp页面展示客户信息
                <c:forEach items="${cs}" var="c">
                    <tr>
                        <td><input type="checkbox">
                        </td>
                        <td>${c.id }</td>
                        <td>${c.name}</td>
                        <td>${c.gender }</td>
                        <td>${c.birthday }</td>
                        <td>${c.cellphone }</td>
                        <td>${c.email }</td>
                        <td>${c.preference }</td>
                        <td>${c.type }</td>
                        <td>${c.description }</td>
                        <td><a>编辑</a>&nbsp;&nbsp;&nbsp;<a>删除</a></td>
                    </tr>
                </c:forEach>
                
    ----------------------------------------------------------
        4.删除操作
            1.在showCustomer.jsp页面的删除连接上添加参数  客户的id
                <a href="${pageContext.request.contextPath}/delByid?id=${c.id}">删除</a>
            2.创建一个CustomerDelByIdServlet,获取请求参数,调用service中删除方法.
            
            问题:如果删除完成后,怎样处理?
                需要重新跳转到查询所有的servlet中,在重新查询数据。
                
    ----------------------------------------------------------------------

5.编辑

            1.查询,做回显示
                    <a href="${pageContext.request.contextPath}/findById?id=${c.id}">编辑</a>
                1.创建CustomerFindByIdServlet,得到要查询的id,调用service,得到Custonmer对象。
                
                2.将customer对象存储到request域,请求转发到customerInfo.jsp页面。
                
                3.在customerInfo.jsp页面展示客户信息
                
                注意:客户的id不能修改,所以使用<input type="hidden">
            2.修改
                
                1.注意使用BeanUtils时的类型转换问题
                    
                2.注意编码问题    
                    post:request.setCharacterEncoding("utf-8");
                    get:手动转换  new String(request.getParameter(name).getBytes("iso8859-1"),"utf-8");
                
                3.进行修改操作
                    String sql = "update customer set name=?,gender=?,birthday=?,cellphone=?,email=?,preference=?,type=?,description=? where id=?";
                    修改完成后,在重新查询一次
                    response.sendRedirect(request.getContextPath() + "/findAll");
                    
================================================================================================
    解决关于回显示时的问题:
        1.性别 应该使用radio
        
            使用自定义标签
                1.定义标签类   extends SimpleTagSupport
                2.定义tld文件
                    <tag>
                        <name>sex</name><!-- 标签名称 -->
                        <tag-class>cn.itcast.customer.tag.GenderTag</tag-class><!-- 标签类 -->
                        <body-content>empty</body-content><!-- 标签体中内容 -->

                        <attribute>
                            <name>gender</name> <!-- 属性名称 -->
                            <required>true</required> <!-- 属性必须有 -->
                            <rtexprvalue>true</rtexprvalue><!-- 属性值可以接收el表达式 -->
                        </attribute>
                    </tag>
                3.在页面上使用
                    1.使用taglib导入
                    2.使用
                        <my:sex gender="${c.gender}" />
                        
    ---------------------------------------------------------------
    使用虚拟主机可以将项目部署成顶级域名
        
        1.在service.xml文件
            1.端口修改为80
            2. 配置主机
              <Host name="www.customer.com"  appBase="myeclipse工作路径\customer(项目名)"
                    unpackWARs="true" autoDeploy="true">

              
                <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
                       prefix="localhost_access_log." suffix=".txt"
                       pattern="%h %l %u %t &quot;%r&quot; %s %b" />

                       <Context path="" docBase="myeclipse工作路径\customer(项目名)\WebRoot" />
              </Host>
            3.在hosts文件中配置

                127.0.0.1  www.customer.com

---------------------------------------------------------------

6.添加

            问题:id是varchar类型,它的获取问题?
                UUID工具类来获取.
                
            完成添加操作:
                1.在showCustomer.jsp页面上添加一个连接,可以直接访问到添加页面 add.jsp
                2.创建add.jsp
                    1.关于生日的日历组件
                        1.导入js
                             <script language="javascript" type="text/javascript" src="${pageContext.request.contextPath}/My97DatePicker/WdatePicker.js"></script>
                        2.在input type=text组件上添加  class,onclick.
                            客户生日:<input type="text" name="birthday" class="Wdate" onclick="WdatePicker()" readonly="readonly"><br>
                    2.关于id问题
                        使用UUID获取
                
                3.创建CustomerAddServlet完成添加操作
                    1.得到所有请求参数封装到Customer对象
                        注意:1.编码问题
                             2.我们使用BeanUtils,注意Date类型转换问题
                             3.要手动封装id.
                    2.调用service完成添加操作
                    
        ------------------------------------------------------------------------            

7.批量删除

            1.完成页面上全选 与全不选操作
                function change(){
                    //1.得到id为main的这个checkbox
                    var main=document.getElementById("main");
                    
                    var flag=main.checked;
                    
                    //2.得到所有name=ck的checkbox
                    var cks=document.getElementsByName("ck");
                    
                    //3.将cks中所有的checkbox的checked值设置为flag
                    for(var i=0;i<cks.length;i++){
                        cks[i].checked=flag;
                    }
                }
            2.完成批量删除
                1.页面上怎样将数据提交到服务器端.
                    1.可以创建一个表单,将表单数据提交就可以。
                        
                    2.直接使用js操作
                        需要手动拼接出url路径
                2.在服务器端怎样批量删除.
                    1.得到所有要删除的id值
                        request.getParameterValues("ck");
                        
                    2.在dao中使用QueryRunner的batch方法
                        
                        batch(sql,Object[][]);
                        
                        注意:参数二维数据,它代表的是每一条sql的参数。
                        
                    {1,2,3}----->{{1},{2},{3}}    
                        
----------------------------------------------------------------------------------------------

8.简单条件查询

            1.页面完成
                在showCustomer.jsp页面上完成
                    <div align="center">
                        <form>
                        <select name="s">
                            <option>请选择条件</option>
                            <option value="name">按姓名查询</option>
                            <option value="cellphone">按手机号查询</option>
                            <option value="description">按描述查询</option>
                        </select>
                        <input type="text" name="msg">
                        <input type="submit" value="查询">
                        </form>
                    </div>
                    问题: select的名称叫什么?每一个option的值是什么?
                        select可以任意起名.
                        option的value名称需要与customer表中的字段名称对应.
                        
            2.创建CustomerSimpleSelectServlet完成条件查询
                
                注意sql语句问题:                

                    String sql="select * from customer where "+field+" like ?";



开发目录结构如下


相关代码如下

CustomerDao.java

package cn.edu.customer.dao;

import java.sql.SQLException;
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 cn.edu.customer.domain.Customer;
import cn.edu.customer.utils.DataSourceUtils;
public class CustomerDao {
		// 查询所有客户
		public List<Customer> findAll() throws SQLException {
			String sql = "select * from customer";

			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
			return runner.query(sql, new BeanListHandler<Customer>(Customer.class));
		}

		public void delById(String id) throws SQLException {
			String sql = "delete from customer where id=?";

			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
			runner.update(sql, id);
		}

		public Customer findById(String id) throws SQLException {
			String sql = "select * from customer where id=?";
			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
			return runner.query(sql, new BeanHandler<Customer>(Customer.class), id);
		}

		public void update(Customer c) throws SQLException {

			String sql = "update customer set name=?,gender=?,birthday=?,cellphone=?,email=?,preference=?,type=?,description=? where id=?";

			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

			runner.update(sql, c.getName(), c.getGender(), c.getBirthday(),
					c.getCellphone(), c.getEmail(), c.getPreference(), c.getType(),
					c.getDescription(), c.getId());
		}
		public void add(Customer c) throws SQLException {
			String sql = "insert into customer values(?,?,?,?,?,?,?,?,?)";

			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

			runner.update(sql, c.getId(), c.getName(), c.getGender(),
					c.getBirthday(), c.getCellphone(), c.getEmail(),
					c.getPreference(), c.getType(), c.getDescription());
		}

		public void delSelect(String[] id) throws SQLException {

			String sql = "delete from customer where id=?";
			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
			Object[][] ids = new Object[id.length][1];

			for (int i = 0; i < id.length; i++) {
				ids[i][0] = id[i];
			}

			runner.batch(sql, ids);
		}

		// 条件查询
		// field 相当于字段名称
		// msg 相当于字段值
		public List<Customer> simpleSelect(String field, String msg)
				throws SQLException {
			String sql = "select * from customer where " + field + " like ?";

			QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

			return runner.query(sql, new BeanListHandler<Customer>(Customer.class),
					"%" + msg + "%");
		}
}

Customer.java

package cn.edu.customer.domain;

import java.util.Date;



public class Customer {
	// Id 编号 varchar(40)
		// name 客户姓名 varchar(20)
		// gender 性别 varchar(10)
		// birthday 生日 date
		// cellphone 手机 varchar(20)
		// email 电子邮件 varchar(40)
		// preference 客户爱好 varchar(100)
		// type 客户类型 varchar(40)
		// description 备注 varchar(255)

		private String id;
		private String name;
		private String gender;
		private Date birthday;
		private String cellphone;
		private String email;
		private String preference;
		private String type;
		private String description;

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public String getGender() {
			return gender;
		}

		public void setGender(String gender) {
			this.gender = gender;
		}

		public Date getBirthday() {
			return birthday;
		}

		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}

		public String getCellphone() {
			return cellphone;
		}

		public void setCellphone(String cellphone) {
			this.cellphone = cellphone;
		}

		public String getEmail() {
			return email;
		}

		public void setEmail(String email) {
			this.email = email;
		}

		public String getPreference() {
			return preference;
		}

		public void setPreference(String preference) {
			this.preference = preference;
		}

		public String getType() {
			return type;
		}

		public void setType(String type) {
			this.type = type;
		}

		public String getDescription() {
			return description;
		}

		public void setDescription(String description) {
			this.description = description;
		}

		@Override
		public String toString() {
			return "Customer [id=" + id + ", name=" + name + ", gender=" + gender
					+ ", birthday=" + birthday + ", cellphone=" + cellphone
					+ ", email=" + email + ", preference=" + preference + ", type="
					+ type + ", description=" + description + "]";
		}

}

CustomerService

package cn.edu.customer.service;

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

import cn.edu.customer.dao.CustomerDao;
import cn.edu.customer.domain.Customer;



public class CustomerService {
	private CustomerDao dao=new CustomerDao();
	
	//查询所有客户信息操作
	public List<Customer> findAll() throws SQLException {
		
		return dao.findAll();
	}
	//根据id删除
	public void delById(String id) throws SQLException {
		
		dao.delById(id);
	}
	//根据id查询
	public Customer findById(String id) throws SQLException {
		return dao.findById(id);
	}
	//修改客户信息
	public void update(Customer c) throws SQLException {

		dao.update(c);
	}
	// 添加客户信息
	public void add(Customer c) throws SQLException {
		dao.add(c);
		}

	// 批量删除
	public void delSelect(String[] id) throws SQLException {
		dao.delSelect(id);
		}

	// 条件查询
	public List<Customer> simpleSelect(String field, String msg)
		throws SQLException {
			return dao.simpleSelect(field, msg);
		}
}

GenderTag.java

package cn.edu.customer.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class GenderTag extends SimpleTagSupport{
	private String gender;

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	@Override
	public void doTag() throws JspException, IOException {

		StringBuffer buff = new StringBuffer();

		if ("男".equals(gender)) {
			buff.append("<input type='radio' name='gender' value='男' checked='checked'>男<input type='radio' name='gender' value='女'>女<br>");
		} else {
			buff.append("<input type='radio' name='gender' value='男'>男<input type='radio' name='gender' value='女' checked='checked'>女<br>");
		}

		this.getJspContext().getOut().write(buff.toString());

	}
}

DataSourceUtils.java

package cn.edu.customer.utils;

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

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

	private static ComboPooledDataSource cpds = new ComboPooledDataSource();

	public static Connection getConnection() throws SQLException {
		return cpds.getConnection();
	}

	public static DataSource getDataSource() {
		return cpds;
	}

}

IdUtils.java

package cn.edu.customer.utils;

import java.util.UUID;



public class IdUtils {
	public static String getUUID(){
		return UUID.randomUUID().toString().replaceAll("-","");
	}
	
	// public static void main(String[] args) {
	// System.out.println(getUUID());
	// }
}

CustomerAddServlet

package cn.edu.customer.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

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.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import cn.edu.customer.domain.Customer;
import cn.edu.customer.service.CustomerService;
import cn.edu.customer.utils.IdUtils;

public class CustomerAddServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 1.得到所有请求参数,封装到javaBean
		Customer c = new Customer();

		DateConverter dc = new DateConverter(); // 这是一个日期类型转换器.
		dc.setPattern("yyyy-MM-dd");

		try {
			ConvertUtils.register(dc, java.util.Date.class);
			BeanUtils.populate(c, request.getParameterMap());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		// 需要手动将id封装到Customer对象.
		c.setId(IdUtils.getUUID());
		// 2.调用serivce完成添加操作

		CustomerService service = new CustomerService();

		try {
			service.add(c);
			// 添加成功
			response.sendRedirect(request.getContextPath() + "/findAll");
			return;
		} catch (SQLException e) {
			e.printStackTrace();
			request.setAttribute("add.message", "添加客户信息失败");
			request.getRequestDispatcher("/add.jsp").forward(request, response);
			return;
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

}


CustomerDelByIdServlet

package cn.edu.customer.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

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.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import cn.edu.customer.domain.Customer;
import cn.edu.customer.service.CustomerService;
import cn.edu.customer.utils.IdUtils;

public class CustomerAddServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 1.得到所有请求参数,封装到javaBean
		Customer c = new Customer();

		DateConverter dc = new DateConverter(); // 这是一个日期类型转换器.
		dc.setPattern("yyyy-MM-dd");

		try {
			ConvertUtils.register(dc, java.util.Date.class);
			BeanUtils.populate(c, request.getParameterMap());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		// 需要手动将id封装到Customer对象.
		c.setId(IdUtils.getUUID());
		// 2.调用serivce完成添加操作

		CustomerService service = new CustomerService();

		try {
			service.add(c);
			// 添加成功
			response.sendRedirect(request.getContextPath() + "/findAll");
			return;
		} catch (SQLException e) {
			e.printStackTrace();
			request.setAttribute("add.message", "添加客户信息失败");
			request.getRequestDispatcher("/add.jsp").forward(request, response);
			return;
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

}

CustomerDelSelectServlet

package cn.edu.customer.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

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

import cn.edu.customer.service.CustomerService;

public class CustomerDelSelectServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		// 1.得到所有要删除的客户的id
		String[] id = request.getParameterValues("ck");

		// 2.调用service,完成批量删除
		CustomerService service = new CustomerService();
		try {
			service.delSelect(id);

			response.sendRedirect(request.getContextPath() + "/findAll");
			return;

		} catch (SQLException e) {
			e.printStackTrace();
			response.getWriter().write("批量删除失败");
			return;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

}

CustomerFindAllServlet

package cn.edu.customer.web.servlet;

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

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

import cn.edu.customer.domain.Customer;
import cn.edu.customer.service.CustomerService;

public class CustomerFindAllServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//调用service中查询所有方法
		CustomerService service=new CustomerService();
		try {
			List<Customer> cs=service.findAll();
			
			request.setAttribute("cs", cs);
			//查询到的信息去展示页面
			request.getRequestDispatcher("/showCustomer.jsp").forward(request,
					response);
			return;
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.getWriter().write("查询客户信息失败");
			return;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

}

CustomerFindByIdServlet

package cn.edu.customer.web.servlet;

import java.io.IOException;
import java.sql.SQLException;

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

import cn.edu.customer.domain.Customer;
import cn.edu.customer.service.CustomerService;

public class CustomerFindByIdServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");

		// 1.得到要查询的id
		String id = request.getParameter("id");

		// 2.调用service中根据id查询的方法.
		CustomerService service = new CustomerService();
		try {
			Customer c = service.findById(id);
			//将customer对象存储到request域
			request.setAttribute("c", c);
			//请求转发到customerInfo。jsp页面上,在此展示需要展示的客户信息
			request.getRequestDispatcher("/customerInfo.jsp").forward(request,
					response);
			return;

		} catch (SQLException e) {
			e.printStackTrace();
			response.getWriter().write("根据id查询失败");
			return;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

}

CustomerSimpleSelectServlet

package cn.edu.customer.web.servlet;

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

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

import cn.edu.customer.domain.Customer;
import cn.edu.customer.service.CustomerService;

public class CustomerSimpleSelectServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        // 1.得到请求参数
        String field = request.getParameter("field"); // 字段名称
        String msg = request.getParameter("msg"); // 字段值

        // 2.调用service完成查询操作
        CustomerService service = new CustomerService();

        try {
            List<Customer> cs = service.simpleSelect(field, msg);

            request.setAttribute("cs", cs);

            request.getRequestDispatcher("/showCustomer.jsp").forward(request,
                    response);
            return;

        } catch (SQLException e) {
            e.printStackTrace();
            response.getWriter().write("条件查询失败");
            return;
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);

    }

}



CustomerUpdateServlet

package cn.edu.customer.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

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.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import cn.edu.customer.domain.Customer;
import cn.edu.customer.service.CustomerService;

public class CustomerUpdateServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
				// 处理请求编码,
				request.setCharacterEncoding("utf-8");
				response.setContentType("text/html;charset=utf-8");
				// 1.得到所有请求参数 ,封装到javaBean中.

				Customer c = new Customer();

				DateConverter dc = new DateConverter(); // 这是一个日期类型转换器.
				dc.setPattern("yyyy-MM-dd");

				try {
					ConvertUtils.register(dc, java.util.Date.class);
					BeanUtils.populate(c, request.getParameterMap());
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}

				// 调用service中修改操作
				CustomerService service = new CustomerService();

				try {
					service.update(c);

					// 跳转到CustomerFindAllServlet,就是要重新查询一次
					response.sendRedirect(request.getContextPath() + "/findAll");
					return;

				} catch (SQLException e) {
					e.printStackTrace();
					response.getWriter().write("修改失败");
					return;
				}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

}

c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql:///day19</property>
		<property name="user">root</property>
		<property name="password">123</property>
	</default-config>

</c3p0-config>

add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib  prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib  prefix="my" uri="http://www.edu.cn/tag"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script language="javascript" type="text/javascript" src="${pageContext.request.contextPath}/My97DatePicker/WdatePicker.js"></script>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
	
	${requestScope["add.message"]}<br>
	<form action="${pageContext.request.contextPath}/add" method="post">		
		客户姓名:<input type="text" name="name"><br>		
		客户性别:<input type="radio" name="gender" value="男" checked="checked">男<input type="radio" name="gender" value="女">女	<br>		
		客户生日:<input type="text" name="birthday" class="Wdate" onclick="WdatePicker()" readonly="readonly"><br>
		客户电话:<input type="text" name="cellphone"><br>
		客户邮箱:<input type="text" name="email"><br>
		客户爱好:<input type="text" name="preference"><br>
		客户类型:<input type="text" name="type"><br>
		客户备注:<input type="text" name="description"><br>
		<input type="submit" value="添加">
	</form>
	

  </body>
</html>

customerInfo.jsp

<%@ 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="my" uri="http://www.edu.cn/tag"%>
<!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="${pageContext.request.contextPath}/update" method="post">
		<input type="hidden" name="id" value="${c.id}">
		
		客户姓名:<input type="text" name="name" value="${c.name}"><br>
		
		客户性别:
			<my:sex gender="${c.gender}"/>
			
		<%--<c:if test="${c.gender=='男'}">
			<input type="radio" name="gender" value="男" checked="checked">男
			<input type="radio" name="gender" value="女">女
		</c:if>
		<c:if test="${c.gender!='男'}">
			<input type="radio" name="gender" value="男">男
			<input type="radio" name="gender" value="女" checked="checked">女
		</c:if>		
		--%>
		
	
		
		客户生日:<input type="text" name="birthday" value="${c.birthday}"><br>
		客户电话:<input type="text" name="cellphone" value="${c.cellphone}"><br>
		客户邮箱:<input type="text" name="email" value="${c.email}"><br>
		客户爱好:<input type="text" name="preference" value="${c.preference}"><br>
		客户类型:<input type="text" name="type" value="${c.type}"><br>
		客户备注:<input type="text" name="description" value="${c.description}"><br>
		<input type="submit" value="修改">
	</form>
		
</body>
</html>

showCustomer.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP 'index.jsp' starting page</title>

<script type="text/javascript">
	function del(id) {

		var flag = window.confirm("确认删除吗");

		if (flag) {
			//确认删除
			location.href = "${pageContext.request.contextPath}/delById?id="
					+ id;
		}
	};

	function change() {
		//1.得到id为main的这个checkbox
		var main = document.getElementById("main");

		var flag = main.checked;

		//2.得到所有name=ck的checkbox
		var cks = document.getElementsByName("ck");

		//3.将cks中所有的checkbox的checked值设置为flag
		for ( var i = 0; i < cks.length; i++) {
			cks[i].checked = flag;
		}
	};
	
	function sendDel(){
		document.getElementById("f").submit();//表单提交
		
		var cks = document.getElementsByName("ck");
		
		/*var url="${pageContext.request.contextPath}/delSelect?";
		for(var i=0;i<cks.length;i++){
			if(cks[i].checked){
				var id=cks[i].value;
				url+="id="+id+"&";
			}
		}*/
	};
</script>
</head>

<body>

	<c:if test="${empty cs}">
		无客户信息
	</c:if>


	<c:if test="${not empty cs}">
		<div align="center">
			<form action="${pageContext.request.contextPath}/simpleSelect" method="post">
			<select name="field">
				<option>请选择条件</option>
				<option value="name">按姓名查询</option>
				<option value="cellphone">按手机号查询</option>
				<option value="description">按描述查询</option>
			</select>
			<input type="text" name="msg">
			<input type="submit" value="查询">
			</form>
		</div>
		<br>
		<form action="${pageContext.request.contextPath}/delSelect" method="post" id="f">
			<table border="1" align="center" width="85%">
				<tr>
					<td><input type="checkbox" id="main" onclick="change();">
					</td>
					<td>客户编号</td>
					<td>客户姓名</td>
					<td>客户性别</td>
					<td>客户生日</td>
					<td>客户电话</td>
					<td>客户邮箱</td>
					<td>客户爱好</td>
					<td>客户类型</td>
					<td>客户备注</td>
					<td>操作</td>
				</tr>

				<c:forEach items="${cs}" var="c">
					<tr>
						<td><input type="checkbox" value="${c.id}" name="ck"></td>
						<td>${c.id }</td>
						<td>${c.name}</td>
						<td>${c.gender }</td>
						<td>${c.birthday }</td>
						<td>${c.cellphone }</td>
						<td>${c.email }</td>
						<td>${c.preference }</td>
						<td>${c.type }</td>
						<td>${c.description }</td>
						<td><a
							href="${pageContext.request.contextPath}/findById?id=${c.id}">编辑</a>

							 <a href="javascript:void(0)" onclick="del('${c.id}')">删除</a>
						</td>
					</tr>
				</c:forEach>
				<tr>
					<td colspan="10"><a href="javascript:void(0)" onclick="sendDel();">删除选中</a></td>
					<td><a href="${pageContext.request.contextPath}/add.jsp">添加</a>
					</td>
				</tr>
			</table>
		</form>
	</c:if>

</body>
</html>

success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>

	<a href="${pageContext.request.contextPath}/findAll">查看所有客户信息</a>
  </body>
</html>

               
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值