SSM_CRUD新手练习(6)分页后台控制器编写

 经过测试基础环境已经搭建好了,现在我们开始编写CRUD。

我们来看一下查询的逻辑该怎么写:

1、访问index.jsp页面

2、index.jsp页面发送查询员工的请求

3、EmployeeController来接受请求,查出员工数据

4、来到list.jsp页面进行展示

那么我们先改变一下index.jsp,增加一个跳转动作,发送查询员工的请求,我们的urI用“/emps”表示。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <jsp:forward page="/emp"></jsp:forward>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<script src="static/js/jquery/2.0.0/jquery.min.js"></script>
<link href="static/css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
<script src="staticjs/bootstrap/3.3.6/bootstrap.min.js"></script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body>
</html>

接下来我们创建一个EmployeeController处理这个请求:

import org.springframework.web.bind.annotation.RequestParam;

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

public class EmployeeController {
    @Autowired
    EmployeeService employeeService;
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn ,Model model){
        //引入PageHelper插件
        //在查询之前只要调用startPage(页码,每页有多少记录)
        //紧接着的查询就是一个分页查询
        //使用pageInfo包装查询的结果
        PageHelper.startPage(pn,5);
        List<Employee> emps=employeeService.getAll();
        //封装了详细的分页信息,包括有我们查询出来的数据,传入我们连续显示的页数
        PageInfo page=new PageInfo(emps,5);
        model.addAttribute("pageInfo", page);
    
        return "list";
    }

}

我们观察代码可以看到,该控制器自动注入了一个EmployeeService组件,并调用了它的getAll()方法获取一个List<Employee>集合,包含员工的数据。

因此,我们需要在service包下创建一个EmployeeService类

package com.atguigu.crud.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atguigu.crud.bean.Employee;
import com.atguigu.crud.dao.EmployeeMapper;
@Service
public class EmployeeService {
    @Autowired 
    EmployeeMapper employeeMapper;
     
    public List<Employee> getAll() {
        // TODO Auto-generated method stub
        return employeeMapper.selectByExampleWithDept(null);
    }

}

EmployeeService的getAll()方法调用了employeeMapper中的带部门的查询方法,取出了数据库中的员工。

还有我们使用了PageHelper插件进行分页处理,将查询的分页信息封装在PageInfo对象中,并且该插件的配置文件前面已经配置好了。

下面不急着编写list页面,我们可以先进行测试一下。

原文地址:https://www.cnblogs.com/fankailei/p/9838927.html