ssm框架整合入门系列——查询-分页显示数据

ssm框架整合入门系列——查询-分页显示数据(pageHelper的使用)


查询也就是显示操作,在该项目下具体表现为:

  1. 访问index.jsp页面
  2. index.jsp页面发送出查询员工列表请求
  3. EmployeeController 来接受请求,查出员工数据
  4. 来到list.jsp页面进行展示

修改index.jsp为:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<jsp:forward page="/emps"></jsp:forward>

com.liantao.crud.controller下新建EmployeeController.java

package com.liantao.crud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liantao.crud.bean.Employee;
import com.liantao.crud.service.EmployeeService;

/**
 * 处理员工的crud请求
 * @author liantao.me
 *
 */
@Controller
public class EmployeeController {
    
    
    @Autowired
    EmployeeService employeeService;
    /*
     * 查询员工数据(分页查询)
     * @return
     */
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model){
        
        //引入PageHelper分页插件
        //查询之前需要调用,,传入页码,以及每页的大小
        PageHelper.startPage(pn,5);
        //startPage后面紧跟的是这个查询就是一个分页查询
        List<Employee> emps = employeeService.getAll();
        //使用pageInfo包装查询后的结果,只需要将Pageinfo交给页面就行了
        //封装了详细的分页信息,包括我们查出来的数据,传入连续显示的数据
        PageInfo page = new PageInfo(emps,5);
        model.addAttribute("pageInfo",page);
        return "list";
    }
    
    
}

com.liantao.crud.service下新建EmployeeService.java

package com.liantao.crud.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.liantao.crud.bean.Employee;
import com.liantao.crud.dao.EmployeeMapper;

@Service
public class EmployeeService {
    
    @Autowired
    EmployeeMapper employeeMapper;
    
    /**  
     * 查询所有员工数据(分页查询)
     * @return
     */
    public List<Employee> getAll() {
        // TODO Auto-generated method stub
    
        return employeeMapper.selectByExampleWithDept(null);
    }

}

并引入pageHelper插件,添加dependency:

<!-- 引入pageHelper分页插件 -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.0.0</version>
    </dependency>

然后再mybatis-config.xml中注册,添加plugins(plugins要添加在typeAliases):

<plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
  </plugins>

pageHelp插件使用文档可参照:地址

WEB-INFviews目录下新建list.jsp页面

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
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>员工列表</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="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    This is my JSP page. <br>
  </body>
</html>

单元测试

com.liantao.crud.test新建一个测试类MvcTest.java,添加代码:

package com.liantao.crud.test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.github.pagehelper.PageInfo;
import com.liantao.crud.bean.Employee;

/**
 * 使用Spring测试模块提供的测试请求功能,测试curd请求的正确性
 * @author asus
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
public class MvcTest {
    //传入SpringMvc的ioc
    @Autowired
    WebApplicationContext context;
    
    //虚拟mvc请求,获取到处理结果
    MockMvc mockMvc;
    
    @Before
    public void initMockMvc(){
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }
    @Test
    public void testPage() throws Exception{
        //模拟请求拿到返回值
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "1"))
                            .andReturn();
        
        //请求成功以后,请求域中会有pageInfo,我们可以取出pageInfo进行验证
        MockHttpServletRequest request = result.getRequest();
        
        PageInfo pi = (PageInfo)request.getAttribute("pageInfo");
        System.out.println("当前页码:"+pi.getPageNum());
        System.out.println("总页码:"+pi.getPages());
        System.out.println("总记录数:"+pi.getTotal());
        System.out.println("再也没需要连续显示的页码:");
        int[] nums = pi.getNavigatepageNums();
        for(int i:nums){
            System.out.println(" "+i);
        }
        
        //获取员工数据
        List<Employee> list = pi.getList();
        for(Employee employee : list){
            System.out.println("ID:"+employee.getEmpId()+"==>Name"+employee.getEmpName());
        }
        
        
    }
    
    
}

结果:
MvcTest.java

succeed


用bootstrap编写显示页面

由于,我们Index.jsp的forward,所以我们要编写的页面应该是list.jsp

bootstrap文档:地址

代码如下:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>员工列表</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">
    -->
    <!-- 引入jquery -->
    <script type="text/javascript" src="${path}/ssm-crud/static/js/jquery-1.12.4.js"></script>
    <!-- 引入css、js -->
    <link href="${path}/ssm-crud/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${path}/ssm-crud/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
  </head>
  
  <body>
    <div class="container">
        <!-- 标题 -->
        <div class="row">
            <div class="col-md-12">
                <h1>SSM-CRUD</h1>
            </div>
        </div>
        <!-- 按钮 -->
        <div class="row">
            <div class="col-md-4 col-md-offset-8">
                <button class="btn btn-primary">新增</button>
                <button class="btn btn-danger">删除</button>
            </div>
        </div>
        <!-- 显示表格数据 -->
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover">
                    <tr>
                        <th>#</th>
                        <th>empName</th>
                        <th>gender</th>
                        <th>email</th>
                        <th>deptName</th>
                        <th>操作</th>
                    </tr>
                    <c:forEach items="${pageInfo.list }" var="emp">
                        <tr>
                            <th>${emp.empId }</th>
                            <th>${emp.empName }</th>
                            <th>${emp.gender=="M"?"男":"女" }</th>
                            <th>${emp.email }</th>
                            <th>${emp.department.deptName}</th>
                            <th>
                                <button class="btn btn-primary btn-sm">
                                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                                编辑</button>
                                <button class="btn btn-danger btn-sm">
                                <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                                删除</button>
                            </th>
                        </tr>
                    </c:forEach>
                    
                </table>
            </div>
        </div>
        <!-- 显示分页信息 -->
        <div class="row">
            <!-- 分页文字信息 -->
            <div class="col-md-6">
                当前${pageInfo.pageNum }页,总${pageInfo.pages }页,总${pageInfo.total }条记录
            </div>
            <!-- 分页条信息 -->
            <div class="col-md-6">
                <nav aria-label="Page navigation">
                  <ul class="pagination">
                  <li><a href="${path }/ssm-crud/emps?pn=1">首页</a></li>
                  <!-- 判断是否有上一页,以便显示点击按钮 -->
                  <c:if test="${pageInfo.hasPreviousPage }">
                    <li>    
                      <a href="${path }/ssm-crud/emps?pn=${pageInfo.pageNum-1 }" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                      </a>
                    </li>
                  </c:if>
                    <!-- 遍历页码 -->
                    <c:forEach items="${pageInfo.navigatepageNums }" var="page_Num">
                        <c:if test="${page_Num == pageInfo.pageNum }">
                            <li class="active"><a href="#">${page_Num }</a></li>
                        </c:if>
                        <c:if test="${page_Num != pageInfo.pageNum }">
                            <li><a href="${path }/ssm-crud/emps?pn=${page_Num }">${page_Num }</a></li>
                        </c:if>
                    </c:forEach>        
                    <!-- 判断是否有下一页 -->
                    <c:if test="${pageInfo.hasNextPage }">
                    <li>
                      <a href="${path }/ssm-crud/emps?pn=${pageInfo.pageNum+1 }" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                      </a>
                    </li>
                    </c:if>
                    
                    <li><a href="${path }/ssm-crud/emps?pn=${pageInfo.pages }">末页</a></li>
                  </ul>
                </nav>
            </div>
            
        </div>
    </div>
  </body>
</html>

效果如图:

员工列表

在不用ajax技术,我们是这样请求的。下一篇将在这基础上改为发送ajax请求进行员工数据的查询

猜你喜欢

转载自www.cnblogs.com/famine/p/9911862.html