1、分页靠SQL语句支持。不同数据库的分页语句是不同的
2、MySQL分页语句:
l LIMIT M,N
M:开始记录的索引(第一页的第一条的索引是0)
N:每次取出多少条
取第一页,每次取10条:
select * fromcustomer limit 0,10
取第二页,每次取10条:
select * fromcustomer limit 10,10
取第n页:每次取10条:
M=(n-1)*N;
N=10
l 总共的页数:(每次取10条)
=总记录条数%N==0?总记录条数/N:总记录条数/N+1
3、对客户信息系统查询结果集进行分页
a、设计Page类,封装与分页有关的信息
每页显示10条,0~104
limit x,x
第一个参数:索引:从哪里开始查
第二个参数:长度:要查多少条数据
第一页:
select *from customer limit 0,10;
index:
select *from customer limit (index-1)*10,10;
Insert105.java:插入105条数据
import java.util.Date;
import com.heima.bean.Customer;
import com.heima.dao.CustomerDao;
import com.heima.dao.impl.CustomerDaoImpl;
import com.heima.utils.WebTools;
public class Insert105 {
public static void main(String[] args) {
CustomerDao dao = new CustomerDaoImpl() ;
for (int i = 0; i < 105; i++) {
Customer c = new Customer() ;
c.setId(WebTools.createNewId());
c.setName("郭靖" + (i+1)) ;
c.setCellphone(i + 1) ;
c.setBirthday(new java.sql.Date(new Date().getTime())) ;
c.setEmail("郭靖" + i + "@itcast.cn") ;
c.setGender("1") ;
c.setHobby("吃放,睡觉") ;
c.setType("vip") ;
c.setDescription("哈哈哈哈") ;
dao.add(c) ;
}
}
}
bean:
package com.heima.bean;
import java.io.Serializable;
import java.util.Date;
//create table customer(
// id varchar(100) primary key,
// name varchar(100),
// gender varchar(4),# 1 male 0 female
// birthday date,
// cellphone varchar(20),
// email varchar(40),
// hobby varchar(100),#eat,sleep
// type varchar(40),#vip|normal
// description varchar(255)
// );
public class Customer implements Serializable{
private String id ;
private String name ;
private String gender ;
private Date birthday ;
private int cellphone ;
private String email ;
private String hobby ;
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 int getCellphone() {
return cellphone;
}
public void setCellphone(int cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
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;
}
}
formbean:
CustomerFormBean:
package com.heima.web.formbean;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class CustomerFormBean implements Serializable{
private String id ;
private String name ;
private String gender ;
private String birthday ;
private String cellphone ;
private String email ;
private String[] hobby ;
private String type ;
private String description ;
private Map errors = new HashMap() ;
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 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[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
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;
}
public boolean validate(){
//省略
return true ;
}
}
Page:
package com.heima.web.formbean;
import java.io.Serializable;
import java.util.List;
import com.heima.bean.Customer;
public class Page implements Serializable{
private int currentPageIndex ; //当前页的索引
private int pageCount ; //总共有多少页
private int count = 10; //每页显示多少条数据
private int totalDataCount ; //表中公有多少条数据
private int startIndex = 1; //显示页面索引的起始索引
private int endIndex = 5 ; //显示页面索引的结束索引
private List list ; //页面要显示的所有数据的集合
public Page(int totalCount,int count){
this.totalDataCount = totalCount ;
this.count = count ;
//计算公有多少页
pageCount = (totalCount + count - 1)/count ;
}
public int getCurrentPageIndex() {
return currentPageIndex;
}
public void setCurrentPageIndex(int currentPageIndex) {
this.currentPageIndex = currentPageIndex;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCOunt) {
this.pageCount = pageCOunt;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getTotalDataCount() {
return totalDataCount;
}
public void setTotalDataCount(int totalDataCount) {
this.totalDataCount = totalDataCount;
}
public int getStartIndex() {
return startIndex;
}
public void setStartIndex(int startIndex) {
this.startIndex = startIndex;
}
public int getEndIndex() {
return endIndex;
}
public void setEndIndex(int endIndex) {
this.endIndex = endIndex;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
dao:
package com.heima.dao;
import java.util.List;
import com.heima.bean.Customer;
public interface CustomerDao {
/**
* 添加一个客户
* @param customer 要天剑的客户
* @return 天成成功返回TRUE,否则返回FALSE
*/
public boolean add(Customer customer) ;
/**
* 修改一个客户
* @param customer 要修改的客户
* @return 成功返回TRUE,否则返回FALSE
*/
public boolean update(Customer customer) ;
/**
* 根据客户的主键删除客户
* @param id 要删除客户的编号
* @return 删除成功返回TRUE,否则返回FALSE
*/
public boolean delete(String id) ;
/**
* 获取所有的客户
* @return 返回所有客户的集合
*/
@Deprecated
public List getAllCustomer() ;
/**
* 根据客户的编号查询客户
* @param id 客户的编号
* @return 查出来返回此客户,否则返回null
*/
public Customer findCustomerById(String id) ;
/**
* 根据页面的索引查询此页面的腰显示的数据
* @param currentPageIndex 当前页的索引
* @param count 每页要显示的记录数
* @return 返回此页数据的一个集合
*/
public List getPageList(int currentPageIndex,int count) ;
/**
* 获取表中的所有数据的数量
* @return 返回表中数据的数量
*/
public int getTotalCount() ;
}
dao.impl:
package com.heima.dao.impl;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.heima.bean.Customer;
import com.heima.dao.CustomerDao;
import com.heima.utils.JdbcUtils;
public class CustomerDaoImpl implements CustomerDao {
public boolean add(Customer customer) {
// 拿到连接对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = null;
// 创建预处理命令对象
int n = 0;
try {
pstmt = conn
.prepareStatement("insert into "
+ "customer(id,name,gender,birthday,cellphone,email,hobby,type,description) values(?,?,?,?,?,?,?,?,?)");
// 指定?的值
pstmt.setString(1, customer.getId());
pstmt.setString(2, customer.getName());
pstmt.setString(3, customer.getGender());
pstmt.setDate(4,
new java.sql.Date(customer.getBirthday().getTime()));
pstmt.setInt(5, customer.getCellphone());
pstmt.setString(6, customer.getEmail());
pstmt.setString(7, customer.getHobby());
pstmt.setString(8, customer.getType());
pstmt.setString(9, customer.getDescription());
// 执行sql语句
n = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtils.release(null, pstmt, conn);
}
return n > 0 ? true : false;
}
public boolean update(Customer customer) {
// 拿到连接对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = null;
// 创建预处理命令对象
int n = 0;
try {
pstmt = conn
.prepareStatement("update "
+ "customer set name=?,gender=?,birthday=?,cellphone=?,email=?,hobby=?,type=?,description=? where id = ?");
// 指定?的值
pstmt.setString(1, customer.getName());
pstmt.setString(2, customer.getGender());
pstmt.setDate(3,
new java.sql.Date(customer.getBirthday().getTime()));
pstmt.setInt(4, customer.getCellphone());
pstmt.setString(5, customer.getEmail());
pstmt.setString(6, customer.getHobby());
pstmt.setString(7, customer.getType());
pstmt.setString(8, customer.getDescription());
pstmt.setString(9, customer.getId());
// 执行sql语句
n = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtils.release(null, pstmt, conn);
}
return n > 0 ? true : false;
}
public boolean delete(String id) {
// 拿到连接对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = null;
// 创建预处理命令对象
int n = 0;
try {
pstmt = conn.prepareStatement("delete from customer where id = ?");
// 指定?的值
pstmt.setString(1, id);
// 执行sql语句
n = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtils.release(null, pstmt, conn);
}
return n > 0 ? true : false;
}
public List getAllCustomer() {
// 拿到连接对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
List list = new ArrayList();
// 创建预处理命令对象
try {
pstmt = conn
.prepareStatement("select id,name,gender,birthday,cellphone,email,hobby,type,description from customer");
// 执行sql语句
rs = pstmt.executeQuery();
while (rs.next()) {
// 封装数据
Customer c = new Customer();
try {
String id = URLEncoder.encode(rs.getString("id"), "UTF-8");
c.setId(id);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.setName(rs.getString("name"));
c.setGender(rs.getString("gender"));
c.setBirthday(rs.getDate("birthday"));
c.setCellphone(rs.getInt("cellphone"));
c.setEmail(rs.getString("email"));
c.setHobby(rs.getString("hobby"));
c.setType(rs.getString("type"));
c.setDescription(rs.getString("description"));
list.add(c);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(rs, pstmt, conn);
}
return list;
}
public Customer findCustomerById(String id) {
// 拿到连接对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
// 创建预处理命令对象
try {
pstmt = conn
.prepareStatement("select id,name,gender,birthday,cellphone,email,hobby,type,description from customer where id = '"
+ id + "'");
// 执行sql语句
rs = pstmt.executeQuery();
if (rs.next()) {
// 封装数据
Customer c = new Customer();
c.setId(rs.getString("id"));
c.setName(rs.getString("name"));
c.setGender(rs.getString("gender"));
c.setBirthday(rs.getDate("birthday"));
c.setCellphone(rs.getInt("cellphone"));
c.setEmail(rs.getString("email"));
c.setHobby(rs.getString("hobby"));
c.setType(rs.getString("type"));
c.setDescription(rs.getString("description"));
return c;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(rs, pstmt, conn);
}
return null;
}
public List getPageList(int currentPageIndex, int count) {
// 拿到连接对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
List list = new ArrayList();
// 创建预处理命令对象
try {
pstmt = conn
.prepareStatement("select id,name,gender,birthday,cellphone,email,hobby,type,description from customer order by cellphone limit ?,?");
// 指定?的值
pstmt.setInt(1, (currentPageIndex - 1) * count);
pstmt.setInt(2, count);
// 执行sql语句
rs = pstmt.executeQuery();
while (rs.next()) {
// 封装数据
Customer c = new Customer();
try {
String id = URLEncoder.encode(rs.getString("id"), "UTF-8");
c.setId(id);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.setName(rs.getString("name"));
c.setGender(rs.getString("gender"));
c.setBirthday(rs.getDate("birthday"));
c.setCellphone(rs.getInt("cellphone"));
c.setEmail(rs.getString("email"));
c.setHobby(rs.getString("hobby"));
c.setType(rs.getString("type"));
c.setDescription(rs.getString("description"));
list.add(c);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(null, pstmt, conn);
}
return list;
}
public int getTotalCount() {
// 拿到连接对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null ;
// 创建预处理命令对象
try {
pstmt = conn
.prepareStatement("select count(*) from customer");
// 执行sql语句
rs = pstmt.executeQuery() ;
if(rs.next()) //指向第一条记录
return rs.getInt(1) ;
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.release(null, pstmt, conn);
}
return 0;
}
}
service:
package com.heima.service;
import java.util.List;
import com.heima.bean.Customer;
import com.heima.web.formbean.Page;
public interface CustomerService {
/**
* 添加一个客户
* @param customer 要天剑的客户
* @return 天成成功返回TRUE,否则返回FALSE
*/
public boolean add(Customer customer) ;
/**
* 修改一个客户
* @param customer 要修改的客户
* @return 成功返回TRUE,否则返回FALSE
*/
public boolean update(Customer customer) ;
/**
* 根据客户的主键删除客户
* @param id 要删除客户的编号
* @return 删除成功返回TRUE,否则返回FALSE
*/
public boolean delete(String id) ;
/**
* 获取所有的客户
* @return 返回所有客户的集合
*/
@Deprecated
public List getAllCustomer() ;
/**
* 根据客户的编号查询客户
* @param id 客户的编号
* @return 查出来返回此客户,否则返回null
*/
public Customer findCustomerById(String id) ;
/**
* 根据页面的索引查询本页面的腰显示的数据
* @param currentPageIndex 当前页的索引
* @param count 要显示的记录数
* @return
*/
public Page getPageList(int currentPageIndex,int count) ;
/**
* 获取公有多少页
* @param count 代表的是页面显示的记录数
* @return 返回页面的数量
*/
public int getPageCount(int count) ;
}
service.impl:
package com.heima.service.impl;
import java.util.List;
import com.heima.bean.Customer;
import com.heima.dao.CustomerDao;
import com.heima.dao.impl.CustomerDaoImpl;
import com.heima.service.CustomerService;
import com.heima.web.formbean.Page;
public class CustomerServiceImpl implements CustomerService {
CustomerDao dao = new CustomerDaoImpl() ;
public boolean add(Customer customer) {
return dao.add(customer);
}
public boolean update(Customer customer) {
return dao.update(customer);
}
public boolean delete(String id) {
return dao.delete(id);
}
public List getAllCustomer() {
return dao.getAllCustomer();
}
public Customer findCustomerById(String id) {
return dao.findCustomerById(id);
}
public Page getPageList(int currentPageIndex, int count) {
//查询表中的记录数
int totalCount = dao.getTotalCount() ;
//创建Page对象
Page page = new Page(totalCount,count) ;
page.setCurrentPageIndex(currentPageIndex) ;
//设定页面要显示数据的集合
page.setList(dao.getPageList(currentPageIndex, count)) ;
return page;
}
public int getPageCount(int count) {
//查询表中的记录数
int totalCount = dao.getTotalCount() ;
return (totalCount +count -1) /count ;
}
}
utils:
package com.heima.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
//专门用于数据库的工具类
public class JdbcUtils {
private static String driverClass = "" ;
private static String url = "" ;
private static String user = "" ;
private static String password = "";
static{
ResourceBundle rb = ResourceBundle.getBundle("dbcfg") ;
driverClass = rb.getString("driverClass") ;
url = rb.getString("url") ;
user = rb.getString("user") ;
password = rb.getString("password") ;
try {
Class.forName(driverClass) ;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return DriverManager.getConnection(url, user, password) ;
} catch (SQLException e) {
e.printStackTrace();
}
return null ;
}
public static void release(ResultSet rs ,Statement stmt,Connection conn){
if(rs != null){
try {
rs.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
WebTools:
package com.heima.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import sun.misc.BASE64Encoder;
//用来做一些常用的一些操作
public class WebTools {
//获取一个新的唯一的id
public static String createNewId(){
String id = UUID.randomUUID().toString() ;
MessageDigest md;
try {
md = MessageDigest.getInstance("md5");
byte[] bs = md.digest(id.getBytes()) ;
BASE64Encoder base = new BASE64Encoder() ;
id = base.encode(bs) ;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return id ;
}
}
WebUtils:
package com.heima.utils;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
//专门为页面服务: 封装了页面的信息
public class WebUtils {
public static T fillFormBean(Class clazz,HttpServletRequest request){
T t = null ;
try {
t = clazz.newInstance() ;
BeanUtils.populate(t, request.getParameterMap()) ;
} catch (Exception e) {
e.printStackTrace();
}
return t ;
}
}
web.servlet:
Controller:
package com.heima.web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import com.heima.bean.Customer;
import com.heima.service.CustomerService;
import com.heima.service.impl.CustomerServiceImpl;
import com.heima.utils.WebTools;
import com.heima.utils.WebUtils;
import com.heima.web.formbean.CustomerFormBean;
import com.heima.web.formbean.Page;
//控制请求的转向(流程控制)(前端控制器)
public class Controller extends HttpServlet {
CustomerService cs = new CustomerServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 拿到页面传递的数据
String op = request.getParameter("op");
if ("all".equals(op)) {
listAll(request, response);
} else if ("add".equals(op)) {
addCustomer(request, response);
} else if ("toupdate".equals(op)) {
toUpdate(request, response);
} else if ("update".equals(op)) {
update(request, response);
} else if("delete".equals(op)){
delete(request,response) ;
} else if("delmore".equals(op)){
delMore(request,response) ;
} else if("page".equals(op)) {
pageList(request,response) ;
}
}
//查询特定页面的数据
private void pageList(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
//拿到页面传递的页面索引
String currentPageIndex = request.getParameter("currentPageIndex") ;
//给session中设置两个属性,记录循环的开始结束的值
HttpSession session = request.getSession() ;
//查询一下总共需要多少页
int pageCount = cs.getPageCount(10) ;
//判断页面索引的有效性
int pageIndex = Integer.parseInt(currentPageIndex) ;
if(pageIndex < 1)
pageIndex = 1 ;
if(pageIndex > pageCount)
pageIndex = pageCount ;
//查询第一页的数据
//调用service层完成查询
Page page = cs.getPageList(pageIndex, 10) ;
//根据传递的索引页来判断是否需要改变page对象的startIndex,endIndex
//判断点击的是不是两头的页面
//由于每次点击都会产生一个新的page对象,那对象中的startIndex和endIndex都会恢复到1,5,因此不能将数据记录到page对象
//页面循环的变量应当记录到session中,因为session和每一个浏览器相关联
//第一次访问的时候,默认值是1,5
Integer start = (Integer)session.getAttribute("startIndex") ;
Integer end = (Integer)session.getAttribute("endIndex") ;
if(start == null)
session.setAttribute("startIndex",1) ;
if(end == null){
if(pageCount < 5)
session.setAttribute("endIndex", pageCount) ;
session.setAttribute("endIndex", 5) ;
}
if(pageIndex == (Integer)session.getAttribute("startIndex") && pageIndex != 1){
//说明点击的是最左边
session.setAttribute("startIndex", (Integer)session.getAttribute("startIndex") -1) ;
session.setAttribute("endIndex", (Integer)session.getAttribute("endIndex") -1) ;
}
if(pageIndex == (Integer)session.getAttribute("endIndex") && pageIndex != pageCount){
//说明点击的是最右边
session.setAttribute("startIndex", (Integer)session.getAttribute("startIndex") +1) ;
session.setAttribute("endIndex", (Integer)session.getAttribute("endIndex") +1) ;
}
if(pageIndex < (Integer)session.getAttribute("startIndex") ){
session.setAttribute("startIndex", pageIndex - 1) ;
session.setAttribute("endIndex", pageIndex + 3) ;
if((Integer)session.getAttribute("startIndex") == 1){
session.setAttribute("startIndex", 1) ;
session.setAttribute("endIndex", 5) ;
}
}
if(pageIndex > (Integer)session.getAttribute("endIndex") ){
session.setAttribute("startIndex", pageIndex - 3) ;
session.setAttribute("endIndex", pageIndex + 1) ;
if((Integer)session.getAttribute("endIndex") > pageCount){
session.setAttribute("startIndex", pageCount-4) ;
session.setAttribute("endIndex", pageCount) ;
}
}
// if(pageIndex == page.getStartIndex() && pageIndex != 1){
// //说明点击的是最左边的页面
// page.setStartIndex(page.getStartIndex() -1) ;
// page.setEndIndex(page.getEndIndex() - 1) ;
// }
// if(pageIndex == page.getEndIndex() && pageIndex != pageCount){
// //说明点击的是最右边的索引页面
// page.setStartIndex(page.getStartIndex() + 1) ;
// page.setEndIndex(page.getEndIndex() + 1) ;
// }
//将page对象存入到session中
request.getSession().setAttribute("page", page) ;
//请求重定向到主页面
response.sendRedirect(request.getContextPath() + "/list.jsp") ;
}
//删除多条数据
private void delMore(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
//拿到页面的数据
String ids = request.getParameter("ids") ;
//由于ids后面多了一个逗号,记得去掉
ids = ids.substring(0, ids.length()-1) ;
//拆分字符串
String [] strIds = ids.split(",") ;
System.out.println(strIds[0]);
//循环删除
for (int i = 0; i < strIds.length; i++) {
//调用service层进行删除操作
cs.delete(strIds[i]) ;
}
//转向主页面
pageList(request, response);
}
//删除单个的客户信息
private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//拿到页面传递的数据
String id = request.getParameter("id") ;
//调用service层完成业务逻辑
boolean flag = cs.delete(id) ;
if (!flag) {
// 删除失败
request.getSession().setAttribute("error", "删除失败");
}
// 先重新查询数据库,拿取数据后在转向
pageList(request, response);
}
// 修改客户信息
private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 封装页面的数据
CustomerFormBean cfb = WebUtils.fillFormBean(CustomerFormBean.class,
request);
// 检测数据(省略)
// 拷贝数据到一个JavaBean中
Customer c = new Customer();
// 由于时间是date类型,所以首先注册一个时间转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
// 拷贝数据
try {
BeanUtils.copyProperties(c, cfb);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 处理数据
// 其次由于爱好类型不同,所以bean不会膀臂拷贝数据,需要手动拷贝
// 拿到页面的爱好数组
String[] hobby = cfb.getHobby();
if (hobby != null && hobby.length > 0) {
StringBuffer sb = new StringBuffer(hobby[0]);
for (int i = 1; i < hobby.length; i++) {
sb.append("," + hobby[i]);
}
c.setHobby(sb.toString());
}
// 调用service层完成业务逻辑
boolean flag = cs.update(c);
if (flag) {
// 说明修改成功了,转向主页面
// 先重新查询数据库,拿取数据后在转向
pageList(request, response);
} else {
// 修改失败
request.setAttribute("error", "修改失败");
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
}
// 转向修改页面(查出来用户数据后)
private void toUpdate(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 拿到页面传递的id
String id = request.getParameter("id");
// 调用service层完成业务逻辑(查找用户)
Customer c = cs.findCustomerById(id);
// 将对象存入request对象后转发到修改页面
request.setAttribute("customer", c);
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
// 添加客户信息
private void addCustomer(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 封装页面的数据
CustomerFormBean cfb = WebUtils.fillFormBean(CustomerFormBean.class,
request);
// 检测数据(省略)
// 拷贝数据到一个JavaBean中
Customer c = new Customer();
// 由于时间是date类型,所以首先注册一个时间转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class);
// 拷贝数据
try {
BeanUtils.copyProperties(c, cfb);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 处理数据
// 首先c中没有主键(id),需要创建一个id
c.setId(WebTools.createNewId());
// 其次由于爱好类型不同,所以bean不会膀臂拷贝数据,需要手动拷贝
// 拿到页面的爱好数组
String[] hobby = cfb.getHobby();
if (hobby != null && hobby.length > 0) {
StringBuffer sb = new StringBuffer(hobby[0]);
for (int i = 1; i < hobby.length; i++) {
sb.append("," + hobby[i]);
}
c.setHobby(sb.toString());
}
// 调用service层完成业务逻辑
boolean flag = cs.add(c);
if (flag) {
// 说明添加成功了,转向主页面
// 先重新查询数据库,拿取数据后在转向
pageList(request, response) ;
} else {
// 添加失败
request.setAttribute("error", "添加失败");
request.getRequestDispatcher("/add.jsp").forward(request, response);
}
}
// 显示所有的数据
private void listAll(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 拿到所有的数据
List list = cs.getAllCustomer();
// 将数据存放到session中
request.getSession().setAttribute("list", list);
// 页面重定向到主页面
response.sendRedirect(request.getContextPath() + "/list.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
dbcfg.properties:
list.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jstl/core_rt" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
客户信息
添加
删除
全选全不选
姓名
性别
生日
电话
邮箱
爱好
类型
描述
操作
暂时没有数据
${c.name }
${c.gender=="1"?"男":"女" }
${c.birthday }
${c.cellphone}
${c.email }
${c.hobby }
${c.type=="vip"?"贵宾":"普通用户" }
${c.description }
修改
删除
第${page.currentPageIndex}页/共${page.pageCount }页
|<
${page.currentPageIndex == n?"":""}${n }
>|
跳转
add.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
My JSP 'index.jsp' starting page
添加客户信息
update.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fun"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
My JSP 'index.jsp' starting page
修改客户信息