客戶管理系統---體驗基於資料庫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; } }
②:
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; } }
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>
CustDao=com.dzq.dao.CustDaoImpl
CustService=com.dzq.service.CustServiceImpl
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); } } }
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); } } }
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); }
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); } }*/ }
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); }
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; } }
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); } }
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); } }
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); } }
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); } }
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); } }
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); } }
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); } }
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); } }
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>
<%@ 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>
<%@ 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>
<%@ 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>
<%@ 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>
9.執行截圖:
index.jsp
原始碼下載: