JavaEE学习日志(一百零五): ssm练习之订单模块实现,分页查询,分页助手PageHelper

订单模块

查询所有订单

前端

在这里插入图片描述

<c:forEach items="${orderList}" var="order">
<tr>
	<td><input name="ids" type="checkbox"></td>
	<td>${order.id}</td>

	<td>${order.orderNum}</td>
	<td>
		<fmt:formatDate value="${order.orderTime}" pattern="yyyy-MM-dd HH:mm"></fmt:formatDate>
	</td>
	<td>${order.peopleCount}</td>
	<%--
		支付宝	0
		微信	1
		其他	2
	--%>
	<td>${order.payType==0?"支付宝":order.payType==1?"微信":"其他"}</td>
	<td>${order.orderStatus==0?"未支付":"已支付"}</td>
	<td>
		${order.product.productName}
	</td>


	<td class="text-center">
		<button type="button" class="btn bg-olive btn-xs"
			onclick='location.href="${pageContext.request.contextPath}/pages/order-show.jsp"'>订单</button>
		<button type="button" class="btn bg-olive btn-xs"
			onclick='location.href="${pageContext.request.contextPath}/pages/order-show.jsp"'>查看</button>
	</td>
</tr>
</c:forEach>

OrderController

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;

    /**
     * 查询所有订单
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        //查询所有订单
        List<Order> orderList = orderService.findAll();
        //modelandview
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orderList",orderList);
        modelAndView.setViewName("order-list");
        return modelAndView;
    }
}

OrderService

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderDao orderDao;
    @Override
    public List<Order> findAll() {
        return orderDao.findAll();
    }
}

OrderDao

/**
     * 查询全部订单,需要映射product
     * @return
     */
    @Select("select * from orders")
    @Results({
            @Result(property = "product",column = "productId",javaType = Product.class,
            one = @One(select = "com.itheima.dao.ProductDao.findById"))
    })
    List<Order> findAll();

添加订单的数据回显

前端

在这里插入图片描述

<select class="form-control select2" style="width: 100%"
	name="product.id">
	<%--
		value:给程序员使用
		文本:给客户看
	--%>
	<c:forEach items="${productList}" var="p">
		<option value="${p.id}" >${p.productName}</option>
	</c:forEach>
	
</select>

OrderController

/**
     * 添加订单的数据回显
     * @return
     */
    @RequestMapping("/addUI")
    public ModelAndView addUI(){
        //查询所有产品数据
        List<Product> productList = productService.findAll();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("productList",productList);
        modelAndView.setViewName("order-add");
        return modelAndView;
    }

添加订单

前端

在这里插入图片描述

<form action="${pageContext.request.contextPath}/order/save" method="post">

OrderController

@RequestMapping("/save")
    public String save(Order order){
        orderService.save(order);
        return "redirect:/order/findAll";
    }

OrderService

@Override
    public void save(Order order) {
        orderDao.save(order);
    }

OrderDao

/**
     * 添加订单
     * @param order
     */
    @Insert("insert into orders values(order_seq.nextval,#{orderNum},#{orderTime},#{peopleCount},#{orderDesc},#{payType},#{orderStatus},#{product.id})")
    void save(Order order);

分页查询

手动实现分页查询

PageBean

package com.itheima.domain;

import java.util.List;

/**
 * 分页查询的PageBean对象
 * 需要的参数
 * 总页数 totalPage
 * 总条数 totalCount
 * 分页条数 pageSize
 * 当前页 currentPage
 * 当前页数据 List<E>
 *
 */
public class PageBean<E> {
    private Integer totalPage;
    private Long totalCount;
    private Integer pageSize;
    private Integer currentPage;
    private List<E> list;

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Long totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public List<E> getList() {
        return list;
    }

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

ProductController

/**
     * 查询全部产品
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize){
        PageBean<Product> pageBean = productService.findByPage(currentPage,pageSize);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("pageBean",pageBean);
        modelAndView.setViewName("product-list");
        return modelAndView;
    }

ProductService

/**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PageBean<Product> findByPage(Integer currentPage, Integer pageSize) {
        PageBean<Product> pageBean = new PageBean<>();
        //设置参数
        pageBean.setCurrentPage(currentPage);
        pageBean.setPageSize(pageSize);
        //设置总条数
        Long totalCount = productDao.findTotalCount();
        pageBean.setTotalCount(totalCount);
        //设置总页数
        pageBean.setTotalPage((int)Math.ceil(totalCount*1.0/pageSize));
        //设置每页数据
        Integer startIndex = (currentPage-1)*pageSize+1;
        Integer endIndex = currentPage*pageSize;
        List<Product> productList = productDao.findByPage(startIndex,endIndex);
        pageBean.setList(productList);
        return pageBean;
    }

ProductDao

 /**
     * 获取产品的总条数
     * @return
     */
    @Select("select count(1) from product")
    Long findTotalCount();

    /**
     * 查询每页的数据
     * @param startIndex
     * @param endIndex
     * @return
     */
    @Select("select t.* from(select p.*,rownum rm from product p) t where rm between #{param1} and #{param2} ")
    List<Product> findByPage(Integer startIndex, Integer endIndex);

前端

数据显示

<tbody>
<c:forEach items="${pageBean.list}" var="product">
	<tr>
		<td><input name="ids" type="checkbox" value="${product.id}"></td>
		<td>${product.id}</td>

		<td>${product.productNum}</td>
		<td>${product.productName}</td>
		<td>${product.cityName}</td>
		<td>
			<fmt:formatDate value="${product.departureTime}" pattern="yyyy-MM-dd HH:mm"></fmt:formatDate>
		</td>
		<td>${product.productPrice}</td>
		<td>${product.productDesc}</td>
		<td>${product.productStatus}</td>

		<td class="text-center">
			<button type="button" class="btn bg-olive btn-xs"
					onclick='delOne(${product.id})'>删除</button>
			<button type="button" class="btn bg-olive btn-xs"
				onclick='location.href="all-order-manage-edit.html"'>订单</button>
			<button type="button" class="btn bg-olive btn-xs"
				onclick='location.href="${pageContext.request.contextPath}/product/updateUI?id=${product.id}"'>修改</button>
		</td>
	</tr>
</c:forEach>



</tbody>

分页导航条

<!-- .box-footer-->
<div class="box-footer">
	<div class="pull-left">
		<div class="form-group form-inline">
			总共${pageBean.totalPage}页,共${pageBean.totalCount}条数据。 每页
			<select id="pageSize" onchange="gotoPage(1)" class="form-control">
				<option value="2">2</option>
				<option value="3">3</option>
				<option value="5" selected="selected">5</option>
				<option value="10">10</option>
			</select></div>
	</div>

	<div class="box-tools pull-right">
		<ul class="pagination">
			<li><a href="javascript:gotoPage(1)" aria-label="Previous">首页</a></li>
			<li><a href="javascript:gotoPage(${pageBean.currentPage-1})">上一页</a></li>
			<c:forEach begin="1" end="${pageBean.totalPage}" var="i">
			<li><a href="javascript:gotoPage(${i})">${i}</a></li>
			</c:forEach>
			<li><a href="javascript:gotoPage(${pageBean.currentPage+1})">下一页</a></li>
			<li><a href="javascript:gotoPage(${pageBean.totalPage})" aria-label="Next">尾页</a></li>
		</ul>
	</div>

</div>
<!-- /.box-footer-->

js

$("#pageSize option[value=${pageBean.pageSize}]").prop("selected","selected");

function gotoPage(currentPage) {
	var pageSize = $("#pageSize").val();

	if (currentPage<1){
		return;
	}
	if (currentPage>${pageBean.totalPage}){
		return;
	}
	location.href = "${pageContext.request.contextPath}/product/findAll?currentPage="+currentPage+"&pageSize="+pageSize;
}

分页助手PageHelper

PageHelper是国内非常优秀的一款开源的mybatis分页插件,它支持基本主流与常用的数据库,例如mysql、oracle、mariaDB、DB2、SQLite、Hsqldb等。

网址:https://pagehelper.github.io/

本项目在 github 的项目地址:https://github.com/pagehelper/Mybatis-PageHelper

本项目在 gitosc 的项目地址:http://git.oschina.net/free/Mybatis_PageHelper

引入依赖

 <!--分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>

两种配置方法

都在sqlSessionFactoryBean对象中进行配置

第一种:直接在application-dao.xml中进行配置,且需要指定数据库

<!--sqlSessionFactoryBean对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--引入分页插件  方法一-->
        <property name="plugins">
            <!--注入属性-->
            <array>
                <!--引入插件类型-->
                <bean class="com.github.pagehelper.PageInterceptor">
                    <!--告诉分页插件使用的是什么数据库-->
                    <property name="properties">
                        <props>
                            <!--helperDialect:分页插件的方言-->
                            <prop key="helperDialect">oracle</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>
        
    </bean>

第二种:创建SqlMapConfig.xml,然后再application-dao.xml中引用,不需要指定数据库

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
</configuration>
<!--sqlSessionFactoryBean对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
       
        <!--引入分页插件方法二-->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
    </bean>

分页助手的基本使用

  1. 为分页助手初始化参数,会将参数放入当前线程中
PageHelper.startPage(currentPage,pageSize);
  1. 查询全部,并通过拦截器将参数传递给方法
List<Product> productList = productDao.findAll();
  1. 创建PageInfo对象,相当于PageBean:需要通过构造传入查询的集合对象,也可以传入当前页面要显示的页码数量
PageInfo<Product> pageInfo = new PageInfo<>(productList,5);
  1. 可以获取各种参数,详情可以去PageInfo的pojo中查看
@Override
    public void testFindByPageHelper(Integer currentPage, Integer pageSize) {
        //为分页助手初始化参数
        PageHelper.startPage(currentPage,pageSize);
        //查询全部
        List<Product> productList = productDao.findAll();
        //创建PageInfo对象,相当于PageBean:需要通过构造传入查询的集合对象
        //5:页面最多显示5个页码
        PageInfo<Product> pageInfo = new PageInfo<>(productList,5);
        System.out.println("当前页:"+pageInfo.getPageNum());
        System.out.println("每页条数:"+pageInfo.getPageSize());
        System.out.println("总条数:"+pageInfo.getTotal());
        System.out.println("总页数:"+pageInfo.getPages());
        System.out.println("每页数据:"+pageInfo.getList());
        System.out.println("上一页页码:"+pageInfo.getPrePage());
        System.out.println("下一页页码:"+pageInfo.getNextPage());
        System.out.println("是否第一页:"+pageInfo.isIsFirstPage());
        System.out.println("是否最后一页:"+pageInfo.isIsLastPage());
        System.out.println("页面显示的第一个页码:"+pageInfo.getNavigateFirstPage());
        System.out.println("页面显示的最后一个页码:"+pageInfo.getNavigateLastPage());
    }

项目中使用分页助手

ProductDao
@Select("select * from product")
List<Product> findAll();
ProductService
@Override
    public PageInfo<Product> findByPageHelper(Integer currentPage, Integer pageSize) {
        //指定分页参数
        PageHelper.startPage(currentPage,pageSize);
        //查询全部
        List<Product> productList = productDao.findAll();
        //创建PageInfo对象
        PageInfo<Product> pageInfo = new PageInfo<>(productList,3);

        return pageInfo;
    }
ProductController
/**
     * 分页助手查询
     * @RequestParam请求参数绑定
     *      name:别名value,指定页面参数的名称
     *      required:是否必要参数
     *      defaultValue:默认值
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(
            @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize){
        //准备数据:分页数据
        PageInfo<Product> pageInfo = productService.findByPageHelper(currentPage, pageSize);
        //创建modelandview
        ModelAndView modelAndView = new ModelAndView();
        //添加数据
        modelAndView.addObject("pageInfo",pageInfo);
        //指定页面
        modelAndView.setViewName("product-list");
        return modelAndView;

    }
前端

展示数据

<tbody>
	<%--
		循环标签foreach
		items:要循环的集合对象
		var:循环中的每一个对象
	--%>
	<c:forEach items="${pageInfo.list}" var="product">
	<tr>
		<td><input name="ids" type="checkbox" value="${product.id}"></td>
		<td>${product.id}</td>

		<td>${product.productNum}</td>
		<td>${product.productName}</td>
		<td>${product.cityName}</td>
		<td>
			<%--日期格式化--%>
			<fmt:formatDate value="${product.departureTime}" pattern="yyyy-MM-dd HH:mm"></fmt:formatDate>
		</td>
		<td>${product.productPrice}</td>
		<td>${product.productStatus == 1?"开启":"关闭"}</td>


		<td class="text-center">
			<button type="button" class="btn bg-olive btn-xs"
					onclick='delOne(${product.id})'>删除</button>
			<button type="button" class="btn bg-olive btn-xs"
				onclick='location.href="all-order-manage-edit.html"'>订单</button>
			<button type="button" class="btn bg-olive btn-xs"
				onclick='location.href="${pageContext.request.contextPath}/product/updateUI?id=${product.id}"'>修改</button>
		</td>
	</tr>
	</c:forEach>


</tbody>

分页导航条

div class="box-footer">
	<div class="pull-left">
		<div class="form-group form-inline">
			总共${pageInfo.pages}页,共${pageInfo.total}条数据。 每页
			<select id="pageSize" onchange="gotoPage(1)" class="form-control">
				<option value="2">2</option>
				<option value="3">3</option>
				<option value="5" selected="selected">5</option>
				<option value="10">10</option>

			</select></div>
	</div>

	<div class="box-tools pull-right">
		<ul class="pagination">
			<%--在超链接中访问js函数,必须加前缀:javascript--%>
			<li><a href="javascript:gotoPage(1)" aria-label="Previous">首页</a></li>
			<li><a href="javascript:gotoPage(${pageInfo.prePage})">上一页</a></li>

			<%--begin:从几开始
				end:到哪结束
			--%>
			<c:forEach begin="${pageInfo.navigateFirstPage}" end="${pageInfo.navigateLastPage}" var="i">
				<li><a href="javascript:gotoPage(${i})">${i}</a></li>
			</c:forEach>
			<li><a href="javascript:gotoPage(${pageInfo.nextPage})">下一页</a></li>
			<li><a href="javascript:gotoPage(${pageInfo.pages})" aria-label="Next">尾页</a></li>
		</ul>
	</div>

</div>
<!-- /.box-footer-->

js

$("#pageSize option[value=${pageInfo.pageSize}]").prop("selected","selected");
		function gotoPage(currentPage) {
			//获取每页显示的条数
			var pageSize = $("#pageSize").val();
			if(currentPage<1){
				return;
			}
			if(currentPage>${pageInfo.pages}){
				return;
			}
			location.href = "${pageContext.request.contextPath}/product/findAll?currentPage="+currentPage+"&pageSize="+pageSize;
		}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值