大结果集分页

 

1、分页靠SQL语句支持。不同数据库的分页语句是不同的

2、MySQL分页语句:

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.hcx.bean.Customer;
import com.hcx.dao.CustomerDao;
import com.hcx.dao.impl.CustomerDaoImpl;
import com.hcx.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 + "@hcx.cn") ;
			c.setGender("1") ;
			c.setHobby("吃放,睡觉") ;
			c.setType("vip") ;
			c.setDescription("哈哈哈哈") ;
			
			dao.add(c) ;
		}
	}

}

bean:

 

 

package com.hcx.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.hcx.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<String,String> errors = new HashMap<String,String>() ;

	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.hcx.web.formbean;

import java.io.Serializable;
import java.util.List;

import com.hcx.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<Customer> 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<Customer> getList() {
		return list;
	}

	public void setList(List<Customer> list) {
		this.list = list;
	}
}

 

dao:

 

package com.hcx.dao;

import java.util.List;

import com.hcx.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<Customer> getAllCustomer() ;
	
	/**
	 * 根据客户的编号查询客户
	 * @param id 客户的编号
	 * @return 查出来返回此客户,否则返回null
	 */
	public Customer findCustomerById(String id) ;
	
	/**
	 * 根据页面的索引查询此页面的腰显示的数据
	 * @param currentPageIndex 当前页的索引
	 * @param count 每页要显示的记录数
	 * @return 返回此页数据的一个集合
	 */
	public List<Customer> getPageList(int currentPageIndex,int count) ;
	
	/**
	 * 获取表中的所有数据的数量
	 * @return 返回表中数据的数量
	 */
	public int getTotalCount() ;
}

 

 

 

dao.impl:

 

package com.hcx.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.hcx.bean.Customer;
import com.hcx.dao.CustomerDao;
import com.hcx.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<Customer> getAllCustomer() {
		// 拿到连接对象
		Connection conn = JdbcUtils.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Customer> list = new ArrayList<Customer>();
		// 创建预处理命令对象
		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<Customer> getPageList(int currentPageIndex, int count) {
		// 拿到连接对象
		Connection conn = JdbcUtils.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Customer> list = new ArrayList<Customer>();
		// 创建预处理命令对象
		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.hcx.service;

import java.util.List;

import com.hcx.bean.Customer;
import com.hcx.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<Customer> 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.hcx.service.impl;

import java.util.List;

import com.hcx.bean.Customer;
import com.hcx.dao.CustomerDao;
import com.hcx.dao.impl.CustomerDaoImpl;
import com.hcx.service.CustomerService;
import com.hcx.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<Customer> 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:
JdbcUtils:

 

 

package com.hcx.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.hcx.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.hcx.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

//专门为页面服务: 封装了页面的信息
public class WebUtils {

	public static <T> T fillFormBean(Class<T> 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.hcx.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.hcx.bean.Customer;
import com.hcx.service.CustomerService;
import com.hcx.service.impl.CustomerServiceImpl;
import com.hcx.utils.WebTools;
import com.hcx.utils.WebUtils;
import com.hcx.web.formbean.CustomerFormBean;
import com.hcx.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<Customer> 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:

index.jsp:

 

 

<body>
        <jsp:forward page="/servlet/Controller?op=page¤tPageIndex=1"></jsp:forward>
  </body>

 

 

 

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+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
		#t1{
			width:900px;
		}
		#t2{
			border:1px solid gray; 
			border-collapse: collapse;
			font-size:15px;
			text-align:center;
		}
		#t2 td,th{
			border:1px solid gray;
		}
		#t2 tr:hover{
			background-color: ffccff ;
		}
		
		a{
			text-decoration: none;
		}
	</style>
  </head>
    <script type="text/javascript">
    	function checkAll(flag){
    		//拿到所有的记录
    		var ids = document.getElementsByName("ids") ;
    		//循环设置每一个复选框
    		for(var i = 0 ;i <ids.length ;i++){
    			ids[i].checked = flag ;
    		}
    	}
    	
    	function delmore(){
    		//拿到所有的记录的复选框
    		var ids = document.getElementsByName("ids") ;
    		//循环判断每一个复选框是否选中,构建id字符串
    		var s = "" ;
    		for(var i = 0 ;i<ids.length ;i++){
    			if(ids[i].checked == true){
    				//拿到此复选框的value
    				s += ids[i].value + "," ;
    			}
    		}
    		//数据传递到服务端进行删除
    		window.location = "${pageContext.request.contextPath }/servlet/Controller?op=delmore&ids=" + s + "¤tPageIndex=${page.currentPageIndex}" ;
    	}
    	
    	function jump(index){
    		if("undefined" == typeof(index)){
    			//说明是点击的是超链接
    			//拿到文本框中的数据
    			var n = document.getElementById("pageindex").value ;
    			//判断是否合法
    			if(isNaN(n)){
    				alert("必须填写数字") ;
    				return ;
    			}
    			index = n ;
    		}
    		
    		window.location.href = "${pageContext.request.contextPath }/servlet/Controller?op=page¤tPageIndex=" + index ;
    	}
    </script>

  <body>
        <h1 align ="center">客户信息</h1>
        <hr>
        <table id  = "t1" align = "center">
        	<tr>
        		<td>
        			<a href = "${pageContext.request.contextPath }/add.jsp">添加</a>   
        			<a href = "javascript:delmore()">删除</a>   
        		</td>
        	</tr>
        	<tr>
        		<td>
        			<table width = "100%" id = "t2">
        				 <tr>
        				 	 <th nowrap><input type = "checkbox" id = "all" onclick = "checkAll(this.checked)" >全选全不选</th>
        				 	 <th nowrap>姓名</th>
        				 	 <th nowrap>性别</th>
        				 	 <th nowrap>生日</th>
        				 	 <th nowrap>电话</th>
        				 	 <th nowrap>邮箱</th>
        				 	 <th nowrap>爱好</th>
        				 	 <th nowrap>类型</th>
        				 	 <th nowrap>描述</th>
        				 	 <th nowrap>操作</th>
        				 </tr>
        				 <c:choose>
        				 	<c:when test="${empty page.list}">
        				 		<tr>
        				 			<td colspan = "10" align = "center">暂时没有数据</td>
        				 		</tr>
        				 	</c:when>
        				 	<c:otherwise>
        				 		<c:forEach items="${page.list }" var = "c" >
        				 			 <tr>
			        				 	 <td nowrap><input type = "checkbox" name = "ids" value= "${c.id }" ></td>
			        				 	 <td nowrap>${c.name }</td>
			        				 	 <td nowrap>${c.gender=="1"?"男":"女" }</td>
			        				 	 <td nowrap>${c.birthday }</td>
			        				 	 <td nowrap>${c.cellphone}</td>
			        				 	 <td nowrap>${c.email }</td>
			        				 	 <td nowrap>${c.hobby }</td>
			        				 	 <td nowrap>${c.type=="vip"?"贵宾":"普通用户" }</td>
			        				 	 <td nowrap>${c.description }</td>
			        				 	 <td nowrap>
			        				 	 	<a href = "${pageContext.request.contextPath }/servlet/Controller?op=toupdate&id=${c.id}">修改</a>   
        									<a href = "${pageContext.request.contextPath }/servlet/Controller?op=delete&id=${c.id}¤tPageIndex=${page.currentPageIndex}">删除</a>
			        				 	 </td>
			        				 </tr>
        				 		</c:forEach>
        				 	</c:otherwise>
        				 </c:choose>
        			</table>
        			<table>
        				<tr>
        					<td width = "20%">第<font color =red>${page.currentPageIndex}页</font>/共<font color =red>${page.pageCount }</font>页</td>
        					<td width = "55%">
        						 <a href = "${pageContext.request.contextPath }/servlet/Controller?op=page¤tPageIndex=${page.currentPageIndex - 1}">|<</a>
        						 <c:forEach begin="${startIndex }" end="${endIndex }" var = "n">
        						 	  <a href = "${pageContext.request.contextPath }/servlet/Controller?op=page¤tPageIndex=${n}">${page.currentPageIndex == n?"<font color =red>":"<font>"}${n }</font></a>   
        						 </c:forEach>
        						 <a href = "${pageContext.request.contextPath }/servlet/Controller?op=page¤tPageIndex=${page.currentPageIndex + 1}">>|</a>
        					</td>
        					<td width = "15%">
        						 <input type ="text" size="5" id  = "pageindex"> 
        						 <a href = "javascript:jump()">跳转   </a>
        					</td>
        					<td width = "10%">
        						  <select name = "currentPageIndex" onchange = "jump(this.value)">
        						  		<c:forEach begin="1" end="${page.pageCount }" var = "n">
        						  			<option value = "${n}" ${page.currentPageIndex == n?"selected":"" }>第${n }页</option>
        						  		</c:forEach>
        						  </select>
        					</td>
        				</tr>
        			</table>
        		</td>
        	</tr>
        </table>
  </body>
</html>

 

 

 

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 + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/Birthday-Calendar.js"></script>
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<style type="text/css">
#t1{
	width: 900px;
}
</style>
</head>

<body>
	<h1 align="center">添加客户信息</h1>
	<hr>
	<form action="${pageContext.request.contextPath }/servlet/Controller?op=add" method="post">
		<table id="t1" align="center">
			<tr>
				<td align="right" width = "40%">姓名:</td>
				<td align="left"><input type="text" name="name">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">性别:</td>
				<td align="left"><input type="radio" name="gender" value="1"
					checked>男<input type="radio" name="gender" value="0">女</td>
			</tr>
			<tr>
				<td align="right" width = "40%">生日:</td>
				<td align="left"><input type="text" name="birthday"
					onfocus="new Calendar().show(this)" readonly="readonly">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">电话:</td>
				<td align="left"><input type="text" name="cellphone">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">邮箱:</td>
				<td align="left"><input type="text" name="email">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">爱好:</td>
				<td align="left"><input type="checkbox" name="hobby"
					value="吃饭">吃饭 <input type="checkbox" name="hobby"
					value="睡觉">睡觉 <input type="checkbox" name="hobby"
					value="学java">学Java</td>
			</tr>
			<tr>
				<td align="right" width = "40%">类型:</td>
				<td align="left"><input type="radio" name="type" value="vip"
					checked>贵宾 <input type="radio" name="type" value="common">普通用户
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">描述:</td>
				<td align="left"><textarea rows="5" cols="20"
						name="description">大神留点脚印吧!!!</textarea></td>
			</tr>
			<tr>
				<td align="center" colspan="2"><input type="submit" value="添加">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

 

 

 

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 + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/Birthday-Calendar.js"></script>
<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
<style type="text/css">
#t1{
	width: 900px;
}
</style>
</head>

<body>
	<h1 align="center">修改客户信息</h1>
	<hr>
	<form action="${pageContext.request.contextPath }/servlet/Controller?op=update" method="post">
		<table id="t1" align="center">
		    <tr>
				<td align="left" colspan = "2"><input type="hidden" name="id" value = "${customer.id }">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">姓名:</td>
				<td align="left"><input type="text" name="name" value = "${customer.name }">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">性别:</td>
				<td align="left">
						<input type="radio" name="gender" value="1" ${customer.gender=="1"?"checked":"" }>男
						<input type="radio" name="gender" value="0" ${customer.gender=="0"?"checked":"" }>女</td>
			</tr>
			<tr>
				<td align="right" width = "40%">生日:</td>
				<td align="left"><input type="text" name="birthday"
					onfocus="new Calendar().show(this)" readonly="readonly" value = "${customer.birthday }">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">电话:</td>
				<td align="left"><input type="text" name="cellphone" value = "${customer.cellphone }"> 
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">邮箱:</td>
				<td align="left"><input type="text" name="email" value = "${customer.email }">
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">爱好:</td>
				<td align="left">
						<input type="checkbox" name="hobby"  value="吃饭" ${fun:contains(customer.hobby,"吃饭")?"checked":"" }>吃饭 
				        <input type="checkbox" name="hobby"  value="睡觉" ${fun:contains(customer.hobby,"睡觉")?"checked":"" }>睡觉 
				        <input type="checkbox" name="hobby"  value="学java" ${fun:contains(customer.hobby,"学java")?"checked":"" }>学Java</td>
			</tr>
			<tr>
				<td align="right" width = "40%">类型:</td>
				<td align="left">
					<input type="radio" name="type" value="vip"  ${customer.type=="vip"?"checked":"" }>贵宾
					 <input type="radio" name="type" value="common"  ${customer.type!="vip"?"checked":"" }>普通用户
				</td>
			</tr>
			<tr>
				<td align="right" width = "40%">描述:</td>
				<td align="left"><textarea rows="5" cols="20"
						name="description">${customer.description }</textarea></td>
			</tr>
			<tr>
				<td align="center" colspan="2"><input type="submit" value="保存">
				</td>
			</tr>
		</table>
	</form>
</body>
</html>

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值