客户管理系统---体验基于数据库javaweb的增删改查
添加客户 查询客户列表 修改客户信息 删除客户 条件查询客户信息 分页查询客户
javaee的经典三层架构--工厂类实现解耦
jsp+servlet+service+dao+jdbc+mysql+c3p0+dbutils
com.dzq.web
.service
.dao
.domain
.util
.exception
.factory
JSTL
mysql驱动
beanutils
c3p0包
dbutils包
confing.properties
c3p0-config.xml
create table customer (
id int primary key auto_increment,
name varchar(20),
gender varchar(10),
birthday date,
cellphone varchar(20),
email varchar(40),
preference varchar(100),
type varchar(40),
description varchar(255)
);
字段名 说明 类型
id 编号 int
name 客户姓名 varchar(20)
gender 性别 varchar(10)
birthday 生日 date
cellphone 手机 varchar(20)
email 电子邮件 varchar(40)
preference 客户爱好 varchar(100)
type 客户类型 varchar(40)
description 备注 varchar(255)
工厂类实现解耦
1.添加客户
index.jsp 主页 提供<添加客户>超链接
-->addCust.jsp 添加客户的页面,提供表单允许输入客户信息
-->AddCustServlet 1.封装数据/校验数据 2.调用Service层添加客户的方法 3.重定向回到主页 -->Service 提供添加客户的方法 ,检查客户名是否已经存在,如果存在提示,如果不存在则调用dao增加客户方法
--> Dao 根据用户名查找用户 添加客户
2.查询客户列表
index.jsp 页面中 提供<查询客户列表>超链接
-->ListCustServlet 调用Service中查询所有客户的方法 查到数据后,将查到的数据存入request域中,请求转发listCust.jsp页面展示
-->Service 调用dao中查询所有客户
-->dao中查询所有客户
-->listCust.jsp 页面,遍历list展示所有客户
3.修改客户信息 (查询/修改)
在客户信息列表页面,每一条记录后面都有一个<修改>超链接
-->CustInfoServlet 调用Service中的方法 找到当前客户信息 存入request域后带到updateCust.jsp页面显示
-->updateCust.jsp 显示客户信息,并允许修改
-->UpdateCustServlet 封装数据/调用Service中修改数据的方法
-->Service 修改客户信息的方法,调用dao中的方法进行修改
-->Dao 提供修改客户信息的方法
4.删除客户
在客户信息列表页面,每一条记录后面都有一个<删除>超链接
-->DelCustServlet 获取要删除的客户id,调用Service中删除客户的方法,请求转发到客户列表页面
-->Service 删除客户的方法 调用dao中对应方法
-->Dao中根据id删除客户的方法
5.批量删除客户
在客户信息列表页面的每一条记录之前都有一个复选框,选中后,可以删除
-->BatchDelCustServlet 获取所有要删除的客户的id,调用Service中批量删除客户的方法做删除操作
-->Service中提供批量删除客户的方法,事务的管理
-->dao中删除客户的方法
附源代码:
1.首先是两个javabean
①:
package com.dzq.domain; import java.io.Serializable; import java.util.Date; public class Cust implements Serializable { private int id; private String name; private String gender; private String birthday; private String cellphone; private String email; private String preference; private String type; private String description; public int getId() { return id; } public void setId(int 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 String getBirthday() { return birthday; } public void setBirthday(String 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; } }
Cust.java
②:
package com.dzq.domain; import java.io.Serializable; import java.util.List; public class Page implements Serializable{ private int thispage; private int rowerpage; private int countrow; private int countpage; private int firstpage; private int lastpage; private int prepage; private int nextpage; private List<Cust> list; public int getThispage() { return thispage; } public void setThispage(int thispage) { this.thispage = thispage; } public int getRowerpage() { return rowerpage; } public void setRowerpage(int rowerpage) { this.rowerpage = rowerpage; } public int getCountrow() { return countrow; } public void setCountrow(int countrow) { this.countrow = countrow; } public int getCountpage() { return countpage; } public void setCountpage(int countpage) { this.countpage = countpage; } public int getFirstpage() { return firstpage; } public void setFirstpage(int firstpage) { this.firstpage = firstpage; } public int getLastpage() { return lastpage; } public void setLastpage(int lastpage) { this.lastpage = lastpage; } public int getPrepage() { return prepage; } public void setPrepage(int prepage) { this.prepage = prepage; } public int getNextpage() { return nextpage; } public void setNextpage(int nextpage) { this.nextpage = nextpage; } public List<Cust> getList() { return list; } public void setList(List<Cust> list) { this.list = list; } }
Page.java
2.下面是配置文件:
<?xml version="1.0" encoding="utf-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/cust?Unicode=true&characterEncoding=utf-8</property> <property name="user">root</property> <property name="password"></property> </default-config> </c3p0-config>
c3p0-config.xml
CustDao=com.dzq.dao.CustDaoImpl CustService=com.dzq.service.CustServiceImpl
config.properties
3.下面是工厂类,加载数据文件和数据源
package com.dzq.factory; import java.io.FileReader; import java.util.Properties; public class BasicFactoty { private static BasicFactoty factory=new BasicFactoty(); private static Properties prop=null; private BasicFactoty(){ } public static BasicFactoty getFactory(){ return factory; } static{ prop=new Properties(); try { prop.load(new FileReader(BasicFactoty.class.getClassLoader().getResource("config.properties").getPath())); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /* public CustDao getDao(){ String clazz= prop.getProperty("CustDao"); return (CustDao) Class.forName(clazz).newInstance(); }*/ public <T> T getInstance(Class<T> clazz){ try { String cName=clazz.getSimpleName(); String cImplName=prop.getProperty(cName); return (T) Class.forName(cImplName).newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } }
BasicFactoty.java
4.下面是DaoUntils,用于获取连接和数据源
package com.dzq.util; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DaoUtils { private static DataSource source=new ComboPooledDataSource(); private DaoUtils(){ } public static DataSource getSource(){ return source; } public static Connection getConnection(){ try { return source.getConnection(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } }
DaoUtils.java
5.以下是Dao接口及其实现:
package com.dzq.dao; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import com.dzq.domain.Cust; import com.dzq.domain.Page; public interface CustDao { /** * 根据用户名查找用户 * @param name 用户名 * @return 找到的用户,找不到返回null */ Cust findUserByName(String name); /** * 添加客户 * @param cust */ void addCust(Cust cust); /** * 查询所有用户信息 * @return */ List<Cust> getAllCust(); /** * 根据id查找用户 * @param id */ Cust findUserById(String id); /** * 修改客户信息 * @param cust 最新信息bean */ void updateCust(Cust cust); /** * 根据id删除客户 * @param id */ void delCustById(String id); /** * 删除客户信息,加上了事务处理 * @param id * @throws SQLException */ void delCustByIdWithTrans(Connection conn,String id) throws SQLException; /** * 根据条件查询客户 * @param cust * @return 所有符合条件的客户信息 */ List<Cust> findCustByCond(Cust cust); /** * 查询数据库中一共多少条数据 * @return */ int getCountRow(); /** * 分页查询客户信息 * @param thispage * @param rowperpage * @return */ List<Cust> getCustByPage(int from, int count); }
CustDao.java
package com.dzq.dao; import java.sql.Connection; 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 org.apache.commons.dbutils.handlers.ScalarHandler; import com.dzq.domain.Cust; import com.dzq.domain.Page; import com.dzq.util.DaoUtils; public class CustDaoImpl implements CustDao { @Override public Cust findUserByName(String name) { String sql="select * from customer where name=?"; try{ QueryRunner runner =new QueryRunner(DaoUtils.getSource()); return runner.query(sql, new BeanHandler<Cust>(Cust.class),name); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } @Override public void addCust(Cust cust) { String sql="insert into customer values (null,?,?,?,?,?,?,?,?)"; try{ QueryRunner runner =new QueryRunner(DaoUtils.getSource()); runner.update(sql,cust.getName(),cust.getGender(),cust.getBirthday(),cust.getCellphone(), cust.getEmail(),cust.getPreference(),cust.getType(),cust.getDescription()); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } @Override public List<Cust> getAllCust() { String sql="select * from customer"; try{ QueryRunner runner =new QueryRunner(DaoUtils.getSource()); return runner.query(sql, new BeanListHandler<Cust>(Cust.class)); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } @Override public Cust findUserById(String id) { String sql="select * from customer where id = ?"; try{ QueryRunner runner =new QueryRunner(DaoUtils.getSource()); return runner.query(sql, new BeanHandler<Cust>(Cust.class),id); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } @Override public void updateCust(Cust cust) { String sql="update customer set name=?,gender=?,birthday=?,cellphone=?,email=?,preference=?,type=?,description=? where id=?"; try{ QueryRunner runner =new QueryRunner(DaoUtils.getSource()); runner.update(sql,cust.getName(),cust.getGender(),cust.getBirthday(),cust.getCellphone(), cust.getEmail(),cust.getPreference(),cust.getType(),cust.getDescription(),cust.getId()); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } @Override public void delCustById(String id) { String sql="delete from customer where id =?"; try{ QueryRunner runner =new QueryRunner(DaoUtils.getSource()); runner.update(sql,id); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } @Override public void delCustByIdWithTrans(Connection conn, String id) throws SQLException { String sql="delete from customer where id =?"; QueryRunner runner =new QueryRunner(); runner.update(conn, sql, id); } @Override public List<Cust> findCustByCond(Cust cust) { String sql = "select * from customer where 1=1 "; List<Object> list = new ArrayList<Object>(); if(cust.getName()!=null && !"".equals(cust.getName())){ sql += " and name like ? "; list.add("%"+cust.getName()+"%"); } if(cust.getGender()!=null && !"".equals(cust.getGender())){ sql += " and gender = ? "; list.add(cust.getGender()); } if(cust.getType()!=null && !"".equals(cust.getType())){ sql += " and type = ? "; list.add(cust.getType()); } try{ QueryRunner runner = new QueryRunner(DaoUtils.getSource()); if(list.size()<=0){ //System.out.println("为空"); return runner.query(sql, new BeanListHandler<Cust>(Cust.class)); }else{ //System.out.println("不为空"); return runner.query(sql, new BeanListHandler<Cust>(Cust.class),list.toArray()); } }catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } @Override /*public int getCountRow() { String sql="select count (*) from customer"; System.out.println(sql); QueryRunner runner =new QueryRunner(DaoUtils.getSource()); try { return ((Long)runner.query(sql,new ScalarHandler())).intValue(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }*/ public int getCountRow() { String sql = "select count(*) from customer"; //System.out.println(sql); try{ QueryRunner runner = new QueryRunner(DaoUtils.getSource()); return ((Long)runner.query(sql, new ScalarHandler())).intValue(); }catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } @Override public List<Cust> getCustByPage(int from, int count) { String sql="select * from customer limit ?,?"; try { QueryRunner runner =new QueryRunner(DaoUtils.getSource()); return runner.query(sql, new BeanListHandler<Cust>(Cust.class),from,count); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /*public List<Cust> findCustByCond(Cust cust) { String sql="select * from customer where 1=1"; List<Object> list=new ArrayList<Object>(); if(cust.getName()!=null&&!"".equals(cust.getName())){ sql+=" and name like ?"; list.add("%"+cust.getName()+"%"); } if(cust.getGender()!=null&&!"".equals(cust.getGender())){ sql+="and gender= ?"; list.add(cust.getGender()); } if(cust.getType()!=null&&!"".equals(cust.getType())){ sql+="and type= ?"; list.add(cust.getType()); } try{ QueryRunner runner =new QueryRunner(DaoUtils.getSource()); if(list.size()<=0){ return runner.query(sql, new BeanListHandler<Cust>(Cust.class)); }else{ return runner.query(sql, new BeanListHandler<Cust>(Cust.class),list.toArray()); } }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } }*/ }
CustDaoImpl
6.下面是service接口及其实现
package com.dzq.service; import java.util.List; import com.dzq.domain.Cust; import com.dzq.domain.Page; public interface CustService { /** * 添加客户的方法,封装了用户信息的Bean * @param cust */ void addCust(Cust cust); /** * 查询所有客户信息 * @return所有客户信息 */ List<Cust> getAllCust(); /** * 根据id查询信息 * @param id * @return 客户信息 */ Cust findCustById(String id); /** * 修改客户信息的方法 * @param cust 封装了最新客户信息的bean */ void updateCust(Cust cust); /** * 删除客户信息 * @param id */ void delCustById(String id); /** * 批量删除客户信息,其中会进行事务管理 * @param ids 所有要删除的id组成的数组 */ void batchDel(String[] ids); /** * 根据条件查询客户 * @param cust * @return 所有符合条件的客户信息 */ List<Cust> findCustByCond(Cust cust); /** * 分页查询客户信息 * @param listpage 当前页码信息 * @param rowperpage 每页记录数 * @return 客户信息 */ Page pageCust(int thispage, int rowperpage); }
CustService.java
package com.dzq.service; import java.sql.Connection; import java.util.List; import org.apache.commons.dbutils.DbUtils; import com.dzq.dao.CustDao; import com.dzq.domain.Cust; import com.dzq.domain.Page; import com.dzq.factory.BasicFactoty; import com.dzq.util.DaoUtils; public class CustServiceImpl implements CustService { CustDao dao= BasicFactoty.getFactory().getInstance(CustDao.class); @Override public void addCust(Cust cust) { //1.检查用户名是否已经存在 if(dao.findUserByName(cust.getName())!=null){ throw new RuntimeException("用户名不存在"); } //2.如果没有就调用dao中的方法,增加用户 dao.addCust(cust); } @Override public List<Cust> getAllCust() { return dao.getAllCust(); } @Override public Cust findCustById(String id) { return dao.findUserById(id); } @Override public void updateCust(Cust cust) { dao.updateCust(cust); } @Override public void delCustById(String id) { dao.delCustById(id); } @Override public void batchDel(String[] ids) { Connection conn=DaoUtils.getConnection(); try{ conn.setAutoCommit(false); for(String id:ids){ dao.delCustByIdWithTrans(conn,id); } DbUtils.commitAndCloseQuietly(conn); }catch(Exception e){ DbUtils.rollbackAndCloseQuietly(conn); e.printStackTrace(); throw new RuntimeException(e); } } @Override public List<Cust> findCustByCond(Cust cust) { return dao.findCustByCond(cust); } @Override public Page pageCust(int thispage, int rowperpage) { Page page=new Page(); //--当前页 page.setThispage(thispage); page.setRowerpage(rowperpage); int countrow=dao.getCountRow(); page.setCountrow(countrow); int countpage=countrow/rowperpage+(countrow%rowperpage==0?0:1); page.setCountpage(countpage); page.setFirstpage(1); //int countpage=countrow/rowperpage+(countrow%rowperpage==0?0:1); page.setLastpage(countpage); page.setPrepage(thispage==1?1:thispage-1); page.setNextpage(thispage==countpage?countpage:thispage+1); List<Cust> list= dao.getCustByPage((thispage-1)*rowperpage,rowperpage); page.setList(list); return page; } }
CustServiceImpl
7.下面是几个servlet
package com.dzq.web; import java.io.IOException; 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 org.apache.commons.beanutils.BeanUtils; import com.dzq.domain.Cust; import com.dzq.factory.BasicFactoty; import com.dzq.service.CustService; /** * Servlet implementation class AddCustServlet */ @WebServlet("/AddCustServlet") public class AddCustServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); CustService service=BasicFactoty.getFactory().getInstance(CustService.class); try{ //1.封装校验数据 Cust cust=new Cust(); BeanUtils.populate(cust, request.getParameterMap()); //--单独处理爱好 String []prefs=request.getParameterValues("preference"); StringBuffer buffer=new StringBuffer(); for(String pref:prefs){ buffer.append(pref+","); } String pref=buffer.substring(0, buffer.length()-1); cust.setPreference(pref); //2.调用service方法添加客户 service.addCust(cust); //3.重定向回主页 response.sendRedirect(request.getContextPath()+"/index.jsp"); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
AddCustServlet.java
package com.dzq.web; import java.io.IOException; 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.dzq.factory.BasicFactoty; import com.dzq.service.CustService; @WebServlet("/BatchDelServlet") public class BatchDelServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CustService service=BasicFactoty.getFactory().getInstance(CustService.class); //1.获取所有要删除的客户id String []ids=request.getParameterValues("delId"); //2.调用service中批量删除客户的方法 service.batchDel(ids); //3.重定向到客户列表页面 request.getRequestDispatcher("/ListCustServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
BatchDelServlet
package com.dzq.web; import java.io.IOException; 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.dzq.domain.Cust; import com.dzq.factory.BasicFactoty; import com.dzq.service.CustService; @WebServlet("/CustInfoServlet") public class CustInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); CustService service =BasicFactoty.getFactory().getInstance(CustService.class); //1.获取要查询的客户id String id =request.getParameter("id"); //2.调用service中根据id查询用户的方法 Cust cust=service.findCustById(id); if(cust==null){ throw new RuntimeException("找不到该用户"); } //3.将查到的客户信息,存入request域,请求转发到updateCust.jsp显示 request.setAttribute("cust", cust); request.getRequestDispatcher("/updateCust.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
CustInfoServle
package com.dzq.web; import java.io.IOException; 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.dzq.factory.BasicFactoty; import com.dzq.service.CustService; @WebServlet("/DelCustServlet") public class DelCustServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); CustService service=BasicFactoty.getFactory().getInstance(CustService.class); //1.获取要删除的用户id String id=request.getParameter("id"); //2.调用service中删除 service.delCustById(id); //3.请求转发到客户信息页面 request.getRequestDispatcher("/ListCustServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
DelCustServlet
package com.dzq.web; import java.io.IOException; 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 org.apache.commons.beanutils.BeanUtils; import com.dzq.domain.Cust; import com.dzq.factory.BasicFactoty; import com.dzq.service.CustService; @WebServlet("/FindCustByCondServlet") public class FindCustByCondServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); CustService service=BasicFactoty.getFactory().getInstance(CustService.class); //1.获取条件,封装到bean中 try{ Cust cust=new Cust(); BeanUtils.populate(cust,request.getParameterMap()); //2.根据条件,调用service方法,查询客户 List<Cust> list=service.findCustByCond(cust); request.setAttribute("list", list); //3.重定向到客户信息页面,显示 //System.out.println(list); request.getRequestDispatcher("/listCust.jsp").forward(request, response); }catch(Exception e){ e.printStackTrace(); throw new RuntimeException(e); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
FindCustByCondServlet
package com.dzq.web; import java.io.IOException; 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.dzq.domain.Cust; import com.dzq.factory.BasicFactoty; import com.dzq.service.CustService; /** * Servlet implementation class ListCustServlet */ @WebServlet("/ListCustServlet") public class ListCustServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //1.调用service方法中查询客户信息 CustService service=BasicFactoty.getFactory().getInstance(CustService.class); List<Cust> list=service.getAllCust(); //2。将客户信息存入request域,请求转发到listCust.jsp页面,进行展示 request.setAttribute("list", list); request.getRequestDispatcher("/listCust.jsp").forward(request, response);; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
ListCustServlet
package com.dzq.web; import java.io.IOException; 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.dzq.domain.Cust; import com.dzq.domain.Page; import com.dzq.factory.BasicFactoty; import com.dzq.service.CustService; @WebServlet("/PageCustServlet") public class PageCustServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); CustService service=BasicFactoty.getFactory().getInstance(CustService.class); try { //1.获取当前要显示的页 int thispage=Integer.parseInt(request.getParameter("thispage")); int rowperpage=5; //2.调用service中分页查询 Page page=service.pageCust(thispage,rowperpage); //3.带到pagelist.jsp显示 request.setAttribute("page", page); request.getRequestDispatcher("/pageList.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
PageCustServlet
package com.dzq.web; import java.io.IOException; 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 org.apache.commons.beanutils.BeanUtils; import com.dzq.domain.Cust; import com.dzq.factory.BasicFactoty; import com.dzq.service.CustService; @WebServlet("/UpdateCustServlet") public class UpdateCustServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); CustService service=BasicFactoty.getFactory().getInstance(CustService.class); //1.封装数据,校验数据 try { Cust cust=new Cust(); BeanUtils.populate(cust, request.getParameterMap()); //--单独处理爱好 String []prefs=request.getParameterValues("preference"); StringBuffer buffer=new StringBuffer(); for(String pref:prefs){ buffer.append(pref+","); } String pref=buffer.substring(0, buffer.length()-1); cust.setPreference(pref); //2.调用service中修改客户信息的方法 service.updateCust(cust); //3.重定向到列表页面 request.getRequestDispatcher("/ListCustServlet").forward(request, response); } catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
UpdateCustServlet
8.下面是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> <h1>客户管理系统</h1><hr> <a href="${pageContext.request.contextPath }/addCust.jsp">添加客户</a> <a href="${pageContext.request.contextPath }/ListCustServlet">客户列表</a> <a href="${pageContext.request.contextPath }/PageCustServlet?thispage=1">分页客户信息</a> </body> </html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!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"> function checkAll(allC){ var otherCs=document.getElementsByName("delId") for(var i=0;i<otherCs.length;i++){ otherCs[i].checked=allC.checked; } } </script> </head> <body> <div align="center"> <h1>客户列表页面</h1><hr> <form action="${pageContext.request.contextPath }/FindCustByCondServlet" method="post"> 客户姓名:<input type="text" name="name" value="${param.name }"/> 客户性别: <input type="radio" name="gender" value="" <c:if test="${param.gender==‘‘ }"> checked=‘checked‘ </c:if> />男 <input type="radio" name="gender" value="男" <c:if test="${param.gender==‘男‘ }"> checked=‘checked‘ </c:if> />男 <input type="radio" name="gender" value="女" <c:if test="${param.gender==‘女‘ }"> checked=‘checked‘ </c:if> />女 客户类型: <select name="type"> <option value="" <c:if test="${param.type==‘‘ }"> selected=‘selected‘ </c:if> >钻石客户</option> <option value="钻石客户" <c:if test="${param.type==‘钻石客户‘ }"> selected=‘selected‘ </c:if> >钻石客户</option> <option value="白金客户" <c:if test="${param.type==‘白金客户‘ }"> selected=‘selected‘ </c:if> >白金客户</option> <option value="黄金客户" <c:if test="${param.type==‘黄金客户‘ }"> selected=‘selected‘ </c:if> >黄金客户</option> <option value="白银客户" <c:if test="${param.type==‘白银客户‘ }"> selected=‘selected‘ </c:if> >白银客户</option> <option value="青铜客户" <c:if test="${param.type==‘青铜客户‘ }"> selected=‘selected‘ </c:if> >青铜客户</option> <option value="黑铁客户" <c:if test="${param.type==‘黑铁客户‘ }"> selected=‘selected‘ </c:if> >青铜客户</option> <option value="没牌客户" <c:if test="${param.type==‘没牌客户‘ }"> selected=‘selected‘ </c:if> >没牌客户</option> </select> <input type="submit" value="提交"/> </form> <form action="${pageContext.request.contextPath }/BatchDelServlet" method="post"> <table border="1"> <tr> <th><input type="checkbox" onclick="checkAll(this)"/>全选</th> <th>客户姓名</th> <th>客户性别</th> <th>出生日期</th> <th>手机号码</th> <th>电子邮件</th> <th>客户爱好</th> <th>客户类型</th> <th>个人描述</th> <th>修改</th> <th>删除</th> </tr> <c:forEach items="${requestScope.list }" var="cust"> <tr> <td><input type="checkbox" name="delId" value="${cust.id }"/></td> <td><c:out value="${cust.name }"></c:out></td> <td><c:out value="${cust.gender }"></c:out></td> <td><c:out value="${cust.birthday }"></c:out></td> <td><c:out value="${cust.cellphone }"></c:out></td> <td><c:out value="${cust.email }"></c:out></td> <td><c:out value="${cust.preference }"></c:out></td> <td><c:out value="${cust.type }"></c:out></td> <td><c:out value="${cust.description }"></c:out></td> <td><a href="${pageContext.request.contextPath }/CustInfoServlet?id=${cust.id}">修改</a></td> <td><a href="${pageContext.request.contextPath }/DelCustServlet?id=${cust.id}">删除</a></td> </tr> </c:forEach> </table> <input type="submit" value="删除选中项"/> </form> </div> </body> </html>
listCust.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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"> function changePage(obj){ if(obj.value==null||obj.value==""){ obj.value=${page.thispage}; return; }else if(isNaN(obj.value)){ alert("必须是数字"); obj.value=${page.thispage}; return; }else if(obj.value<0||obj.value>${page.countpage}){ alert("页码必须在有效范围内"); obj.value=${page.thispage}; return; }else{ window.location.href="${pageContext.request.contextPath }/PageCustServlet?thispage="+obj.value; } } </script> </head> <body> <div align="center"> <h1>分页查询客户信息</h1><hr> <table border="1"> <tr> <th>客户姓名</th> <th>客户性别</th> <th>出生日期</th> <th>手机号码</th> <th>电子邮件</th> <th>客户爱好</th> <th>客户类型</th> <th>个人描述</th> <th>修改</th> <th>删除</th> </tr> <c:forEach items="${requestScope.page.list }" var="cust"> <tr> <td><c:out value="${cust.name }"></c:out></td> <td><c:out value="${cust.gender }"></c:out></td> <td><c:out value="${cust.birthday }"></c:out></td> <td><c:out value="${cust.cellphone }"></c:out></td> <td><c:out value="${cust.email }"></c:out></td> <td><c:out value="${cust.preference }"></c:out></td> <td><c:out value="${cust.type }"></c:out></td> <td><c:out value="${cust.description }"></c:out></td> <td><a href="${pageContext.request.contextPath }/CustInfoServlet?id=${cust.id}">修改</a></td> <td><a href="${pageContext.request.contextPath }/DelCustServlet?id=${cust.id}">删除</a></td> </tr> </c:forEach> </table> 共 ${page.countrow }记录 共 ${page.countpage }页 <a href="${pageContext.request.contextPath }/PageCustServlet?thispage=${page.firstpage}">首页</a> <a href="${pageContext.request.contextPath }/PageCustServlet?thispage=${page.prepage}">上一页</a> <c:if test="${page.countpage<=5 }"> <c:set var="begin" value="1" scope="page"></c:set> <c:set var="end" value="${page.countpage }" scope="page"></c:set> </c:if> <c:if test="${page.countpage>5 }"> <c:choose> <c:when test="${page.thispage<=3 }"> <c:set var="begin" value="1" scope="page"></c:set> <c:set var="end" value="5" scope="page"></c:set> </c:when> <c:when test="${page.thispage>=page.countpage-2 }"> <c:set var="begin" value="1" scope="page"></c:set> <c:set var="end" value="${page.countpage }" scope="page"></c:set> </c:when> <c:otherwise> <c:set var="begin" value="${page.thispage-2 }" scope="page"></c:set> <c:set var="end" value="${page.countpage+2 }" scope="page"></c:set> </c:otherwise> </c:choose> </c:if> <c:forEach begin="${begin }" end="${end }" step="1" var="i"> <c:if test="${i==page.thispage }"> ${i } </c:if> <c:if test="${i!=page.thispage }"> <a href="${pageContext.request.contextPath }/PageCustServlet?thispage=${i}">${i }</a> </c:if> </c:forEach> <a href="${pageContext.request.contextPath }/PageCustServlet?thispage=${page.nextpage}">下一页</a> <a href="${pageContext.request.contextPath }/PageCustServlet?thispage=${page.lastpage}">尾页</a> 跳转到<input type="text" value="${page.thispage }" style="width: 40px;" onchange="changePage(this)"/>页 </div> </body> </html>
pageList.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> <div align="center"> <h1>客户管理系统_添加客户</h1><hr> <form action="${pageContext.request.contextPath }/AddCustServlet" method="post"> <table> <tr> <td>客户姓名:</td> <td><input type="text" name="name"/></td> </tr> <tr> <td>客户性别:</td> <td> <input type="radio" name="gender" value="男"/>男 <input type="radio" name="gender" value="女"/>女 </td> </tr> <tr> <td>出生日期:</td> <td><input type="text" name="birthday"/></td> </tr> <tr> <td>手机号码:</td> <td><input type="text" name="cellphone"/></td> </tr> <tr> <td>电子邮件:</td> <td><input type="text" name="email"/></td> </tr> <tr> <td>客户爱好:</td> <td> <input type="checkbox" name="preference" value="篮球"/>篮球 <input type="checkbox" name="preference" value="足球"/>足球 <input type="checkbox" name="preference" value="排球"/>排球 <input type="checkbox" name="preference" value="棒球"/>棒球 <input type="checkbox" name="preference" value="网球"/>网球 </td> </tr> <tr> <td>客户类型:</td> <td> <select name="type"> <option value="钻石客户">钻石客户</option> <option value="白金客户">白金客户</option> <option value="黄金客户">黄金客户</option> <option value="白银客户">白银客户</option> <option value="青铜客户">青铜客户</option> <option value="黑铁客户">黑铁客户</option> <option value="没牌客户">没牌客户</option> </select> </td> </tr> <tr> <td>描述信息:</td> <td> <textarea name="description" rows="6" cols="40"></textarea> </td> </tr> <tr> <td><input type="submit" value="添加客户"/></td> </tr> </table> </form> </div> </body> </html>
addCust.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <!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> <div align="center"> <h1>修改客户信息</h1><hr> <form action="${pageContext.request.contextPath }/UpdateCustServlet" method="post"> <input type="hidden" name="id" value="${cust.id }"/> <table> <tr> <td>客户姓名:</td> <td><input type="text" name="name" value="${cust.name }" readonly="readonly" style="background:silver;"/></td> </tr> <tr> <td>客户性别:</td> <td> <input type="radio" name="gender" value="男" <c:if test="${cust.gender==‘男‘ }"> checked=‘checked‘ </c:if> />男 <input type="radio" name="gender" value="女" <c:if test="${cust.gender==‘女‘ }"> checked=‘checked‘ </c:if> />女 </td> </tr> <tr> <td>出生日期:</td> <td><input type="text" name="birthday" value="${cust.birthday }"/></td> </tr> <tr> <td>手机号码:</td> <td><input type="text" name="cellphone" value="${cust.cellphone }"/></td> </tr> <tr> <td>电子邮件:</td> <td><input type="text" name="email" value="${cust.email }"/></td> </tr> <tr> <td>客户爱好:</td> <td> <input type="checkbox" name="preference" value="篮球" <c:forTokens items="${cust.preference }" delims="," var="pref"> <c:if test="${pref==‘篮球‘ }"> checked=‘checked‘ </c:if> </c:forTokens> />篮球 <input type="checkbox" name="preference" value="足球" <c:if test="${fn:contains(cust.preference,‘足球‘) }"> checked=‘checked‘ </c:if> />足球 <input type="checkbox" name="preference" value="排球" <c:if test="${fn:contains(cust.preference,‘排球‘) }"> checked=‘checked‘ </c:if>/>排球 <input type="checkbox" name="preference" value="棒球" <c:if test="${fn:contains(cust.preference,‘棒球‘) }"> checked=‘checked‘ </c:if> />棒球 <input type="checkbox" name="preference" value="网球" <c:if test="${fn:contains(cust.preference,‘网球‘) }"> checked=‘checked‘ </c:if> />网球 </td> </tr> <tr> <td>客户类型:</td> <td> <select name="type"> <option value="钻石客户" <c:if test="${cust.type==‘钻石客户‘ }"> selected=‘selected‘ </c:if> >钻石客户</option> <option value="白金客户" <c:if test="${cust.type==‘白金客户‘ }"> selected=‘selected‘ </c:if> >白金客户</option> <option value="黄金客户" <c:if test="${cust.type==‘黄金客户‘ }"> selected=‘selected‘ </c:if> >黄金客户</option> <option value="白银客户" <c:if test="${cust.type==‘白银客户‘ }"> selected=‘selected‘ </c:if> >白银客户</option> <option value="青铜客户" <c:if test="${cust.type==‘青铜客户‘ }"> selected=‘selected‘ </c:if> >青铜客户</option> <option value="黑铁客户" <c:if test="${cust.type==‘黑铁客户‘ }"> selected=‘selected‘ </c:if> >青铜客户</option> <option value="没牌客户" <c:if test="${cust.type==‘没牌客户‘ }"> selected=‘selected‘ </c:if> >没牌客户</option> </select> </td> </tr> <tr> <td>描述信息:</td> <td> <textarea name="description" rows="6" cols="40">${cust.description }</textarea> </td> </tr> <tr> <td><input type="submit" value="修改客户"/></td> </tr> </table> </form> </div> </body> </html>
updateCust.jsp
9.运行截图:
index.jsp
源码下载: