Java研学-SSM综合案例(三)

三 前端页面

1 department

input.jsp

javascript 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>部门新增或者修改</title>
</head>
<body>
<h3>部门编辑</h3>
    <form action="/department/saveOrUpdate" method="post">
        <input type="hidden" name="id" value="${department.id}">
        <input type="text" name="name" placeholder="名称" value="${department.name}"><br/>
        <input type="text" name="sn" placeholder="缩写" value="${department.sn}"><br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>

list.jsp

javascript 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>部门列表</title>
    <script>
        function goPage(currentPage) {
            document.getElementById("currentPage").value = currentPage;
            document.forms[0].submit();
        }
    </script>
</head>
<body>
<h3>部门信息列表</h3>
<a href="/department/input">新增</a>
<!-- 查询的表单 -->
<form action="/department/listAll" method="post">
    <input type="hidden" name="currentPage" id="currentPage" value="1"/>
</form>

<table width="800px" cellpadding="0" cellspacing="0" align="center" border="1px">
    <tr>
        <td>ID</td>
        <td>名称</td>
        <td>缩写</td>
        <td>操作</td>
    </tr>
    <%--部门动态数据展示--%>
    <c:forEach items="${pageResult.data}" var="dept">
        <tr>
            <td>${dept.id}</td>
            <td>${dept.name}</td>
            <td>${dept.sn}</td>
            <td>
                <a href="/department/delete?id=${dept.id}">删除</a>
                <a href="/department/input?id=${dept.id}">修改</a>
            </td>
        </tr>
    </c:forEach>
    <tr align="center">
        <td colspan="9">
            <a href="javascript:goPage(1);">首页</a>
            <a href="javascript:goPage(${pageResult.prevPage});">上一页</a>
            <a href="javascript:goPage(${pageResult.nextPage});">下一页</a>
            <a href="javascript:goPage(${pageResult.totalPage});">尾页</a>
            当前:${pageResult.currentPage}/${pageResult.totalPage}
            总条数:${pageResult.totalCount}
        </td>
    </tr>
</table>
</body>
</html>

2 employee

input.jsp

javascript 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>员工编辑</h1>
<form action="/employee/saveOrUpdate" method="POST">
	<input type="hidden" name="id" value="${emp.id}">
	员工账号:<input type="text" name="username" value="${emp.username}"><br>
	员工姓名:<input type="text" name="name" value="${emp.name}"><br>
	<c:if test="${empty emp}">
		员工密码:<input type="text" name="password" ><br>
	</c:if>
	员工邮箱:<input type="text" name="email" value="${emp.email}"><br>
	员工年龄:<input type="text" name="age" value="${emp.age}"><br>
	员工部门:
		<select name="dept.id">
	     <%--动态展示部门信息--%>
			<c:forEach items="${departments}" var="dept">
				<option	value="${dept.id}" ${dept.id==emp.dept_id?'selected':''}>${dept.name}</option>
			</c:forEach>
		</select><br/>
	是否管理员:<input type="checkbox" name="admin" value="1" ${emp.admin==true?'checked':''}><br>
	<input type="submit" value="提交">
</form>
</body>
</html>

list.jsp

javascript 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>

    <script type="text/javascript">
        function goPage(pageNo) {
            //1:获取表单对象
            var form = document.forms[0];
            form.currentPage.value = pageNo;
            form.submit();
        }
    </script>
</head>
<body>
<h1>员工列表</h1>
<a href="/employee/input">添加</a>
<form action="/employee/query" method="post">
    <table border="1" cellpadding="0" cellspacing="0" width="60%">
        <tr>
            <td colspan="8">
                关键字:<input type="text" name="keyword" value="${qo.keyword}">
                部门:<select name="deptId">
                <option value="">全部</option>
                <%--动态展示部门信息--%>
                <c:forEach items="${departments}" var="dept">
                    <option value="${dept.id}" ${dept.id==qo.deptId?'selected':''}>${dept.name}</option>
                </c:forEach>
            </select>
                <input type="submit" value="查询"/>
            </td>
        </tr>
        <tr>
            <td>编号</td>
            <td>名称</td>
            <td>姓名</td>
            <td>email</td>
            <td>年龄</td>
            <td>是否管理员</td>
            <td>部门名称</td>
            <td>操作</td>
        </tr>
        <c:forEach items="${pageResult.data}" var="emp" varStatus="vs">
            <tr>
                <td>${vs.count}</td>
                <td>${emp.username}</td>
                <td>${emp.name}</td>
                <td>${emp.email}</td>
                <td>${emp.age}</td>
                <td>${emp.admin==true?'是':'否'}</td>
                <td>${emp.dept.name}</td>
                <td>
                    <a href="/employee/input?id=${emp.id}">编辑</a>
                    <a href="/employee/delete?id=${emp.id}">删除</a>
                </td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="8" align="center">
                <a href="javascript:;" onclick="goPage(1)">首页</a>
                <a href="javascript:;" onclick="goPage(${pageResult.prevPage})">上一页</a>
                <a href="javascript:;" onclick="goPage(${pageResult.nextPage})">下一页</a>
                <a href="javascript:;" onclick="goPage(${pageResult.totalPage})">末页</a>
                每页显示:<select name="pageSize" onchange="goPage(1)">
                <option value="2" ${pageResult.pageSize == 2 ? 'selected' : ''}>2</option>
                <option value="4" ${pageResult.pageSize == 4 ? 'selected' : ''}>4</option>
                <option value="6" ${pageResult.pageSize == 6 ? 'selected' : ''}>6</option>
            </select>
                ${pageResult.currentPage }/${pageResult.totalPage } 页
                跳转:<input type="text" name="currentPage" style="width: 30px" value="${pageResult.currentPage}">
                <input type="submit" value="GO"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

3 首页 -- index.jsp

java 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>项目首页</title>
</head>
<body>
<p><a href="/department/listAll">查询部门</a></p>
<p><a href="/employee/query">查询员工</a></p>
</body>
</html>

三 Controller 层

1 DepartmentController

java 复制代码
@Controller
@RequestMapping("department")
public class DepartmentController {
    /*注入业务逻辑层对象*/
    @Autowired
    private DepartmentService departmentService;

    /*查询部门*/
    @RequestMapping("selectAll")
    public String selectAll(Model model) {
        List<Department> departmentList = departmentService.listAll();
        model.addAttribute("departmentList", departmentList);
        return "department/list";
    }

    /*跳转到增加或修改页面*/
    @RequestMapping("input")
    public String input(Long id, Model model) {
        /*根据id判断是否做修改*/
        if (id != null) {
            //根据id查询
            Department department = departmentService.get(id);
            //将部门对象存储到作用域
            model.addAttribute("department", department);
        }
        return "department/input";
    }

    /*保存增加或修改*/
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Department department) {
        if (department.getId() != null) {
            //执行修改操作
            departmentService.update(department);
        } else {
            //执行增加操作
            departmentService.save(department);
        }
        //跳转查询
        return "redirect:/department/listAll";
    }

    /*删除部门*/
    @RequestMapping("delete")
    public String delete(Long id) {
        departmentService.delete(id);
        return "redirect:/department/listAll";
    }

    /*分页查询部门*/
    @RequestMapping("listAll")
    public String listAll(Model model,
                          @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                          @RequestParam(value = "pageSize", required = false, defaultValue = "2") Integer pageSize
    ) {
        QueryObject qo = new QueryObject();
        qo.setCurrentPage(currentPage);
        qo.setPageSize(pageSize);
        PageResult<Department> pageResult = departmentService.query(qo);
        model.addAttribute("pageResult", pageResult);
        return "department/list";
    }
}

2 EmployeeController

java 复制代码
@Controller
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private DepartmentService departmentService;

    /*查询所有*/
    @RequestMapping("listAll")
    public String listAll(Model model) {
        List<Employee> employees = employeeService.listAll();
        model.addAttribute("employees", employees);
        return "employee/list";
    }

    /*跳转到增加或查询页面*/
    @RequestMapping("input")
    public String input(Model model, Long id) {
        //查询部门信息
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
        if (id != null) {
            //查询员工信息
            Employee employee = employeeService.get(id);
            model.addAttribute("emp", employee);
        }
        return "employee/input";
    }

    /*增加或修改保存*/
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Employee employee) {
        if (employee.getId() == null) {
            employeeService.save(employee);
        } else {
            employeeService.update(employee);
        }
        return "redirect:/employee/listAll";
    }

    /*删除*/
    @RequestMapping("delete")
    public String delete(Long id) {
        employeeService.delete(id);
        return "redirect:/employee/listAll";
    }

    /*分页查询所有*/
    @RequestMapping("query")
    public String query(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        PageResult<Employee> pageResult = employeeService.query(qo);
        model.addAttribute("pageResult", pageResult);
        //查询所有部门信息
        List<Department> departments = departmentService.listAll();
        model.addAttribute("departments", departments);
        return "employee/list";
    }
}

四 Service 层

1 接口

DepartmentService

java 复制代码
public interface DepartmentService {
    void delete(Long id);
    void save(Department department);
    Department get(Long id);
    List<Department> listAll();
    void update(Department department);
    /*分页查询*/
    public PageResult<Department> query(QueryObject qo);
}

EmployeeService

java 复制代码
public interface EmployeeService {
    int delete(Long id);
    int save(Employee record);
    Employee get(Long id);
    List<Employee> listAll();
    int update(Employee record);
    /*分页查询*/
    public  PageResult<Employee> query(EmployeeQueryObject qo);
}

2 实现类

DepartmentServiceImpl

java 复制代码
@Service
public class DepartmentServiceImpl implements DepartmentService {
    /*注入mapper*/
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public void delete(Long id) {
        departmentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save(Department department) {
        departmentMapper.insert(department);
    }

    @Override
    public Department get(Long id) {
        Department department = departmentMapper.selectByPrimaryKey(id);
        return department;
    }

    @Override
    public List<Department> listAll() {
        List<Department> departmentList = departmentMapper.selectAll();
        return departmentList;
    }

    @Override
    public void update(Department department) {
        departmentMapper.updateByPrimaryKey(department);
    }

    /*分页查询*/
    @Override
    public PageResult<Department> query(QueryObject qo) {
        //查询总条数
        int totalCount = departmentMapper.selectForCount(qo);
        if (totalCount == 0) {
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), 0, Collections.emptyList());
        }
        //分页查询部门
        List<Department> departmentList = departmentMapper.selectForList(qo);
        //创建返回的分页对象
        PageResult<Department> pageResult = new PageResult<>(qo.getCurrentPage(),
                qo.getPageSize(), totalCount, departmentList);
        return pageResult;
    }
}

EmployeeServiceImpl

java 复制代码
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public int delete(Long id) {
        return employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int save(Employee employee) {
        return employeeMapper.insert(employee);
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public int update(Employee employee) {
        return employeeMapper.updateByPrimaryKey(employee);
    }

    @Override
    public PageResult<Employee> query(EmployeeQueryObject qo) {
        int totalCount = employeeMapper.selectForCount(qo);
        if (totalCount == 0) {
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), 0, Collections.emptyList());
        }
        List<Employee> empList = employeeMapper.selectForList(qo);
        PageResult<Employee> pageResult = new PageResult<>(qo.getCurrentPage(), qo.getPageSize(),
                totalCount, empList);
        return pageResult;
    }
}

五 分页与模糊

1 分页实体类

QueryObject

java 复制代码
@Setter
@Getter
public class QueryObject {
    // 当前页
    private int currentPage = 1;
    // 每页条数
    private int pageSize = 2;
    public int getStart(){
        return (currentPage - 1) * pageSize;
    }
}

PageResult

java 复制代码
@Setter
@Getter
public class PageResult<T> {
    private int currentPage; // 页面传的
    private int pageSize; // 页面传的
    private List<T> data; // 数据库查询
    private int totalCount; // 数据库查询

    private int totalPage; // 总页数
    private int prevPage; // 上一页
    private int nextPage; // 下一页

    public PageResult(int currentPage, int pageSize, int totalCount, List<T> data) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
        this.data = data;
        this.totalCount = totalCount;

        // 加入判断,节省计算性能
        if (totalCount <= pageSize) {
            this.totalPage = 1;
            this.prevPage = 1;
            this.nextPage = 1;
            return;
        }
        this.totalPage = this.totalCount % this.pageSize == 0
                ? this.totalCount / this.pageSize : this.totalCount / this.pageSize + 1;
        this.nextPage = this.currentPage + 1 <= this.totalPage ? this.currentPage + 1 : this.totalPage;
        this.prevPage = this.currentPage - 1 >= 1 ? this.currentPage - 1 : 1;
    }
}

2 模糊

EmployeeQueryObject

java 复制代码
@Setter
@Getter
public class EmployeeQueryObject extends QueryObject{
    private String keyword;//根据姓名和邮箱模糊查询
    private Long deptId; // 若这个值为 null 情况,就不根据部门过滤数据
}
相关推荐
明月看潮生12 分钟前
青少年编程与数学 02-003 Go语言网络编程 15课题、Go语言URL编程
开发语言·网络·青少年编程·golang·编程与数学
雷神乐乐16 分钟前
File.separator与File.separatorChar的区别
java·路径分隔符
小刘|21 分钟前
《Java 实现希尔排序:原理剖析与代码详解》
java·算法·排序算法
南宫理的日知录23 分钟前
99、Python并发编程:多线程的问题、临界资源以及同步机制
开发语言·python·学习·编程学习
逊嘘40 分钟前
【Java语言】抽象类与接口
java·开发语言·jvm
Half-up42 分钟前
C语言心型代码解析
c语言·开发语言
morris1311 小时前
【SpringBoot】Xss的常见攻击方式与防御手段
java·spring boot·xss·csp
Source.Liu1 小时前
【用Rust写CAD】第二章 第四节 函数
开发语言·rust
monkey_meng1 小时前
【Rust中的迭代器】
开发语言·后端·rust
余衫马1 小时前
Rust-Trait 特征编程
开发语言·后端·rust