```
分页:limit ?,?
参数1 : startIndex 开始索引.
参数2 : pageSize 每页显示的个数
n 表示第几页 给定一个特殊的单词 pageNumber
select * from product;
第一页显示五条数据:
select * from product LIMIT 0 , 5;
第二页显示五条数据
select * from product LIMIT 5 , 5;
第三页显示五条数据
select * from product LIMIT 10 , 5;
第N页显示五条数据
select * from product LIMIT (pageNumber-1)*pageSize , pageSize;
如果只有一个参数 表示 第一页 显示几个数据
select * from product LIMIT 5;
简单分页查询步骤:
1.sql : select from table limit ?,?
2.startIntdex : 开始索引 不可以是负数
3.pageSize : 每页显示的个数
4.pageNumber : 用户访问的当前页
5.由页面发起传入 pageNumber 和 pageSize(目前写死) 在service层中进行计算startIndex
6.公式 (pageNumber-1)*pageSize
高级分页查询:
将service返回的六个参数,封装成一个PageBean
两个传的
pageNumber,pageSize.
两个查的
totalRecord,data
两个算的
startIndex,totalPage
在service编写代码逻辑 --> 将所有的代码逻辑封装到PageBean中
/*
以后专门用来处理分页的数据:
泛型的定义:
1:方法级别的定义,修饰和返回值之间
2:类级别泛型定义,类名后
public class PageBean
/*
一共六个参数:
2个传入:
pageNumber : 表示当前页
pageSize : 表示每页显示个数
2个查询
data : 分页的数据
totalRecord : 总记录数
2个计算
startIndex : 开始索引
totalPage : 总页数
private int pageNumber;
private int pageSize;
private int totalRecodr;
private int startIndex;
private int totalPage;
private List
public int getStartIndex() {
startIndex = (pageNumber - 1)*pageSize;
}
public int getTotalPage() {
if(totalRecord % pageSize == 0) {
totalPage = totalRecord / pageSize;
}else {
totalPage = totalRecord / pageSize + 1;
}
return totalPage;
}
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
}
开发中真实案例--前五后四动态条 - 扩展 - 前四后五
开发中应用:
//循环的开始
private int start;
//循环结束
private int end;
//计算 开始 和 结束的数据
private void jisuan() {
//总页数有没有可能小于10
//小于 10 不需要前四后五的动态条
if(getTotalPage() < 10) {//必须调用getTotalPage() 因为totalPage需要提前计算
start = 1;
end = totalPage;//最后一页等于最大页数
}else {
//总页数一定大于10 需要前四后五动态条
start = pageNumber - 4;
end = pageNumber + 5;
//如果start < 1 表示 当前1 2 3 4 总共显示10页
if(start < 1) {
start = 1;
end = 10;
}
//如果end > totalPage 需要 计算start值
if(end > totalPage) {
end = totalPage;
start = totalPage - 9;
}
}
}
案例:代码体现
public class ProductServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获得页面传递的参数 用来执行某段代码
String method = request.getParameter("method");
ProductService pService = new ProductService();
CategoryService cService = new CategoryService();
//根据页面功能执行某段特殊的代码
if("findAll".equals(method)){
/**
* 1.类型问题 两种解决方式: 1.正则 2.try
* 2.索引不可以是负数
*/
//1.获得
// 获得分页的数据 pageNumber
String pageNumberStr = request.getParameter("pageNumber");
int pageNumber = 1;
try {
//如果是a 强转失败 赋值操作没有成功 pageNumber = 1
pageNumber = Integer.valueOf(pageNumberStr);
if(pageNumber < 1 ){
pageNumber = 1;
}
} catch (Exception e) {
}
int pageSize = 2;
//2.处理
//List
PageBean
//3.响应
//3.1 将数据存到request
request.setAttribute("pageBean", pageBean);
//3.2 请求转发给jsp
request.getRequestDispatcher("/admin/product/product_list.jsp").forward(request, response);
return;
}
//添加商品前查询分类的数据
if("addProductUI".equals(method)){
//1.获得
//2.处理
//2.1 调用service 查询出所有分类 返回值 List
List
//3.响应
//3.1 将数据存到request
request.setAttribute("cList", cList);
//3.2 请求转发给product_add.jsp
request.getRequestDispatcher("/admin/product/product_add.jsp").forward(request, response);
return;
}
//添加商品数据
if("addProduct".equals(method)){
//1.获得
//1.1 获得map
Map
//1.2 创建Product
Product product = new Product();
//1.3 封装数据
BeanUtils.populate(product, map);
//1.4 手动封装数据
product.setPid( UUID.randomUUID().toString().replace("-", "") );//主键会随机生成
product.setPimage("products/1/c_0001.jpg");
product.setPdate(new Date().toLocaleString());
product.setIs_hot(0);//0表示非热门
product.setPflag(0);//0表示未下架
//2.处理
//调用service保存
pService.save(product);
//3.响应
//重定向到查询所有的案例
response.sendRedirect(request.getContextPath() +"/ProductServlet?method=findAll");
return;
}
//根据pid查询出商品的信息
if("findByPid".equals(method)){
//1.获得
//获得pid的编号
String pid = request.getParameter("pid");
//2 处理
//2.1 商品数据
Product product = pService.findByPid(pid);
//2.2 分类的数据
List
//3 响应
request.setAttribute("product", product);
request.setAttribute("cList", cList);
request.getRequestDispatcher("/admin/product/product_edit.jsp").forward(request, response);
return;
}
//修改商品数据的代码
if("editProduct".equals(method)){
//1.获得
//1.1 获得map集合
Map
//1.2 创建product对象
Product product = new Product();
//1.3 封装
BeanUtils.populate(product, map);
//2.处理
//2.1 调用service修改
boolean flag = pService.update(product);
//3.响应
//3.1 重定向到查询所有的案例
if(flag){
//成功
response.sendRedirect(request.getContextPath() + "/ProductServlet?method=findAll");
}
return ;
}
//根据pid删除商品
if("deleteByPid".equals(method)){
//1.获得
//获得pid
String pid = request.getParameter("pid");
//2.处理
int count = pService.deleteByPid(pid);
//3.响应
if(count > 0){
response.sendRedirect(request.getContextPath() + "/ProductServlet?method=findAll");
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public static void main(String[] args) {
System.out.println(UUID.randomUUID().toString().replace("-", ""));
}
}
public class ProductService {
/*public PageBean
//创建一个即将被返回的对象 PageBean
PageBean
ProductDao dao = new ProductDao();
//将pageNumber 转换成startIndex
int startIndex = (pageNumber - 1) * pageSize;
//查询当前页的2条数据
List
//查询总记录数
int totalRecord = dao.findRecord();
//计算总页数
int totalPage = 0;
if(totalRecord % pageSize == 0 ){
totalPage = totalRecord / pageSize;
}else{
totalPage = totalRecord / pageSize + 1;
}
//赋值
pageBean.setData(data);
pageBean.setPageNumber(pageNumber);
pageBean.setPageSize(pageSize);
pageBean.setStartIndex(startIndex);
pageBean.setTotalPage(totalPage);
pageBean.setTotalRecord(totalRecord);
return pageBean;
}*/
public PageBean
//创建一个即将被返回的对象 PageBean
PageBean
ProductDao dao = new ProductDao();
//查询当前页的2条数据
List
//查询总记录数
int totalRecord = dao.findRecord();
//赋值
pageBean.setData(data);
pageBean.setTotalRecord(totalRecord);
return pageBean;
}
public List
ProductDao dao = new ProductDao();
return dao.findAll();
}
public void save(Product product) throws SQLException {
ProductDao dao = new ProductDao();
dao.save(product);
}
public Product findByPid(String pid) throws SQLException {
ProductDao dao = new ProductDao();
return dao.findByPid(pid);
}
public boolean update(Product product) throws SQLException {
ProductDao dao = new ProductDao();
return dao.update(product);
}
public int deleteByPid(String pid) throws SQLException {
ProductDao dao = new ProductDao();
return dao.deleteByPid(pid);
}
}
package com.baidu.domain;
public class Product {
/*
`pid` VARCHAR(32) NOT NULL,
`pname` VARCHAR(50) DEFAULT NULL, #商品名称
`market_price` DOUBLE DEFAULT NULL, #商场价
`shop_price` DOUBLE DEFAULT NULL, #商城价
`pimage` VARCHAR(200) DEFAULT NULL, #商品图片路径
`pdate` DATE DEFAULT NULL, #上架时间
`is_hot` INT(11) DEFAULT NULL, #是否热门:0=不热门,1=热门
`pdesc` VARCHAR(255) DEFAULT NULL, #商品描述
`pflag` INT(11) DEFAULT 0, #商品标记:0=未下架(默认值),1=已经下架
`cid` VARCHAR(32) DEFAULT NULL, #分类id*/
private String pid;
private String pname;
private double market_price;
private double shop_price;
private String pimage;
private String pdate;
private int is_hot;
private String pdesc;
private int pflag;
private String cid;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getMarket_price() {
return market_price;
}
public void setMarket_price(double market_price) {
this.market_price = market_price;
}
public double getShop_price() {
return shop_price;
}
public void setShop_price(double shop_price) {
this.shop_price = shop_price;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public String getPdate() {
return pdate;
}
public void setPdate(String pdate) {
this.pdate = pdate;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
public int getPflag() {
return pflag;
}
public void setPflag(int pflag) {
this.pflag = pflag;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
}
public class ProductDao {
/**
* 分页的dao
* @param startIndex
* @param pageSize
* @return
* @throws SQLException
*/
public List
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql =" select * from product limit ?,? ";
Object [] params = {
startIndex , pageSize
};
return queryRunner.query(sql, new BeanListHandler
}
/**
* 计算总记录数
* @return
* @throws SQLException
*/
public int findRecord() throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql =" select count(*) from product ";
Object [] params = {
};
Object object = queryRunner.query(sql, new ScalarHandler(), params);
return Integer.valueOf(object.toString());
}
public List
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql =" select * from product order by pdate desc ";
Object [] params = {};
return queryRunner.query(sql, new BeanListHandler
}
public void save(Product product) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql =" insert into product values(?,?,?,?,?,?,?,?,?,?) ";
Object [] params = {
product.getPid() , product.getPname() , product.getMarket_price() ,
product.getShop_price() , product.getPimage() , product.getPdate() ,
product.getIs_hot() , product.getPdesc() , product.getPflag() ,
product.getCid()
};
queryRunner.update(sql, params);
}
public Product findByPid(String pid) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql =" select * from product where pid = ? ";
Object [] params = {pid};
return queryRunner.query(sql, new BeanHandler
}
public boolean update(Product product) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = " update product set pname = ? , shop_price = ? , pdesc = ? , cid = ? where pid = ? ";
Object [] params = {
product.getPname() , product.getShop_price() , product.getPdesc() ,
product.getCid() , product.getPid()
};
return queryRunner.update(sql, params) > 0 ;
}
public int deleteByPid(String pid) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = " delete from product where pid = ? ";
Object [] params = {
pid
};
return queryRunner.update(sql, params) ;
}
/**
* 处理乱码的工具类
*
*/
public class EncodingFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
try {
//处理post乱码
request.setCharacterEncoding("utf-8");
//处理响应
response.setHeader("content-type", "text/html;charset=utf-8");
//处理get乱码
HttpServletRequest myRequest = (HttpServletRequest)Proxy.newProxyInstance(
EncodingFilter.class.getClassLoader(),
request.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//可以对getParameter进行增强 get提交方式
//1.判断是get请求方式
String requestMethod= request.getMethod();
if("GET".equalsIgnoreCase(requestMethod)){
//get提交 只对getParameter方法进行拦截
String methodName = method.getName();
if("getParameter".equals(methodName)){
//get方式 并且 调用的getParameter方法
//获得以前乱码 return 不乱码
String tempValue = request.getParameter(args[0].toString());
//如果没有获得数据 防止空指针
if(tempValue == null){
return null;
}
return new String(tempValue.getBytes("iso-8859-1"),"utf-8");
}
}
//不需要增强
return method.invoke(request, args);
}
});
//放行
chain.doFilter(myRequest, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
jsp代码:
<%-- 获得数据 并遍历 --%>
onmouseout="this.style.backgroundColor = '#fff';">
${product.cid}
${product.pname}
${product.shop_price}
${product.pdesc}
<%--编辑 --%>
<%--查询 --%>
<%--删除 ctrl + q --%>
<%--提示删除 --%>
<%-- 获得数据 并遍历 --%>
//javascript 需要在写在 header标签中
function deleteByPid(pid){
//alert(pid);
//提示用户
var flag = confirm("您确定要删除信息吗?");
if(flag){
//确定删除
//访问服务器删除的Servlet
//修改地址栏 跳转路径 等效我们自己点击超链接
location.href="${pageContext.request.contextPath}/ProductServlet?method=deleteByPid&pid="+pid;
}
}
条件查询:
1: 先在首页上查询分类数据,并且遍历显示
分析:
select * from product where cid = ? and pname = ?;
含有的可能性:
1.两者都有.
2.两者都没有.
3.有cid但没有pname
4.没有cid但有pname
select count(*) from product where 1=1;
伪代码:
SQL = " select * from product where 1=1 ";
if(cid != null) {
SQL += " and cid = ? "
}
if(pname != null) {
SQL += " and pname like ? "
}
1: 修改表单 action属性,method属性,name属性,自定义的method判断逻辑.
2: 调用Servlet
a : 获得 cid和pname
b : 处理 调用service 调用dao(重要)
c : 响应 - 将数据存到request里,请求转发给product_list.jsp
3.对jsp页面进行改造
条件查询注意事项:
1 . Dao的sql部分,拼接的问题,使用 where 1=1 解决了脏读、不可重复读、
2 . Dao的参数拼接部分,使用List接收数据,最后将list转换成数组,解决.
3 . 查询完以后将数据返回给页面,但还需要加上,用户传入后台的cid和pname;
切记:条件查询 不可以 和 分页 同一个项目 但以后 条件查询需要和分页结合
4 . 如果条件查询和分页需要做到同一个项目,需要处理参数问题.
5 . PageBean 查询总记录数 --> 如果加入条件查询,查询总记录数时需要加上条件.
案例:代码体现
public class ProductServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获得页面传递的参数 用来执行某段代码
String method = request.getParameter("method");
ProductService pService = new ProductService();
CategoryService cService = new CategoryService();
//根据页面功能执行某段特殊的代码
if("findAll".equals(method)){
//执行查询所有的代码
//1.获得
//1.31 获得cid
String cid = request.getParameter("cid");
//1.2 获得pname
String pname = request.getParameter("pname");
//2.处理
List
List
//3.响应
//3.1 将数据存到request
request.setAttribute("pList", pList);
request.setAttribute("cList", cList);
request.setAttribute("cid", cid);
request.setAttribute("pname", pname);
//3.2 请求转发给jsp
request.getRequestDispatcher("/admin/product/product_list.jsp").forward(request, response);
return;
}
public class ProductDao {
/**
* 条件查询
* @param cid
* @param pname
* @return
* @throws SQLException
*/
public List
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = " select * from product where 1=1 ";
//定义一个List 作用 用来保存参数
List
//cid判断
if(cid != null && !"".equals(cid)){
sql += " and cid = ? ";
paramList.add(cid);
}
//pname判断
if(pname != null && !"".equals(pname)){
sql += " and pname like ? ";
paramList.add("%"+pname+"%");
}
//数组的缺陷 长度固定 集合的长度不固定 集合最后转换成数组
Object [] params = paramList.toArray();
return queryRunner.query(sql,new BeanListHandler
}