前面我们做了挺多东西了,接下来要做的就是实际业务部分了。
其实管理之类的业务,都是一个套路,能增,能用表格展示出来,然后能删和改就行。
那么就让我们来完成一个用户管理页面,明白其中的套路吧。
1、首先来添加 JSTL 的包,方便我们再后面在 JSP 里用 JSTL 的标签。


点开 Problems 那,然后点下 Add…

2、然后来创建一组页面。
注意的点:
JSTL 标签的使用请查阅:
http://www.runoob.com/jsp/jsp-jstl.html
本片中只用到其核心库的标签。

这些就是提供增删改查功能的页面了。
add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- 引入 jstl 支持 -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:include flush="true" page="../../includes/admin/header.jsp" />
<p>
添加用户
</p>
<p>
<!-- 直接对当前页面的 URL 进行 POST, 用 HTTP 动词来区分-->
<form action="/admin/users/add?page=<%=request.getParameter("page")%>" method="post">
<!-- 对实体直接这样访问也行,因为生成的时候都写好访问器方法了 -->
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
角色:
<select name="user_role_type">
<!-- 访问过去的时候名称映射规则是这样 -->
<option value="1">管理员</option>
<option value="2">用户</option>
</select>
<br>
<input type="submit" value="添加">
</form>
</p>
<jsp:include flush="true" page="../../includes/admin/footer.jsp" />
edit.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- 引入 jstl 支持 -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:include flush="true" page="../../includes/admin/header.jsp" />
<p>
<!-- 从当前页面的 URL 里获取参数 id,也就是当前编辑的用户id-->
用户编辑 ID:${User.id}
</p>
<p>
<!-- 直接对当前页面的 URL 进行 POST, 用 HTTP 动词来区分-->
<form action="/admin/users/edit?page=<%=request.getParameter("page")%>&id=${User.id}" method="post">
<!-- 对实体直接这样访问也行,因为生成的时候都写好访问器方法了 -->
用户名:<input type="text" name="username" value="${User.username}"><br/>
密码:<input type="password" name="password" value="${User.password}"><br/>
角色:
<select name="user_role_type">
<!-- 访问过去的时候名称映射规则是这样 -->
<option value="1"<c:if test="${User.userRoleType == 1}"> selected</c:if>>管理员</option>
<option value="2"<c:if test="${User.userRoleType == 2}"> selected</c:if>>用户</option>
</select>
<br>
<input type="submit" value="编辑">
</form>
</p>
<jsp:include flush="true" page="../../includes/admin/footer.jsp" />
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- 引入 jstl 支持 -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<jsp:include flush="true" page="../../includes/admin/header.jsp" />
<p>
用户列表<a href="./users/add?page=${currentPage}"> 添加</a>
</p>
<%
//显示提示信息
String msg = (String)session.getAttribute("msg");
if(msg != null) {
out.println("<p>");
out.println(msg);
out.println("</p>");
session.removeAttribute("msg");
}
%>
<p>
<table>
<tr>
<th>ID</th>
<th>用户名</th>
<th>用户角色</th>
<th>操作</th>
</tr>
<c:forEach items="${List}" var="user">
<tr>
<th>${user.getId()}</th>
<th>${user.getUsername()}</th>
<th>
<c:if test="${user.getUserRoleType() == 1}">
管理员
</c:if>
<c:if test="${user.getUserRoleType() == 2}">
用户
</c:if>
</th>
<th>
<a href="./users/delete?id=${user.getId()}&page=${currentPage}">删除</a>
<a href="./users/edit?id=${user.getId()}&page=${currentPage}"> 编辑</a>
</th>
</tr>
</c:forEach>
</table>
</p>
<p>
<c:forEach var="i" begin="1" end="${totalPage}">
<c:if test="${currentPage == i}">
${i}
</c:if>
<c:if test="${currentPage != i}">
<a href="./users?page=${i}">${i}</a>
</c:if>
</c:forEach>
</p>
<jsp:include flush="true" page="../../includes/admin/footer.jsp" />
然后我们管理员的头部文件 header.jsp 里加上这个管理页面的首页链接。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>管理员页面</title>
</head>
<body>
<p>
<a href="/admin">首页</a>
<a href="/admin/users">用户管理</a>
<a href="/admin/page1">页面1</a>
<a href="/admin/page2">页面2</a>
<a href="/logout">登出</a>
</p>
3、然后就在 Controller 包的 Admin 包里创建一个AdminUsersController
package Controllers.Admin;
import Helpers.DbConnection;
import Models.UsersEntity;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class AdminUsersController {
//默认页数
static int PageSize = 3;
/**
* @RequestParam注解的作用是:根据参数名从URL中取得参数值
* @param page
* 页数
* @param model
* 一个域对象,可用于存储数据值
*/
@RequestMapping("/admin/users")
public String index(@RequestParam(value = "page", defaultValue = "1") String page, Model model) {
//创建数据库操作线程
Session db_session = DbConnection.getSession();
try{
//参数预处理
Integer currentPage = Integer.valueOf(page);
//传递当前页面
model.addAttribute("currentPage", currentPage);
//创建初始创建条件
Criteria criteria = db_session.createCriteria(UsersEntity.class);
//每次最多
criteria.setMaxResults(PageSize);
//起始位置
criteria.setFirstResult((currentPage - 1) * PageSize);
//列出所有查询结果
List<UsersEntity> list = criteria.list();
model.addAttribute("List", list);
//获取总记录数,计算总页面数,传递总页面数
int total_page = (int)Math.ceil(((Long) (db_session.createCriteria(UsersEntity.class)
.setProjection(Projections.rowCount())
.uniqueResult())) / Double.valueOf(PageSize));
model.addAttribute("totalPage", total_page);
return "admin/users/index";
}catch(Exception e) {
//添加错误信息
e.printStackTrace();
model.addAttribute("error_msg", " 系统发生了错误!");
return "admin/fail";
}finally {
//用完这个 数据库的 Session 记得关了
db_session.close();
}
}
/**
* @RequestParam注解的作用是:根据参数名从URL中取得参数值
* @param id
* 用户 id
* @param page
* 当前页数
* @param model
* 一个域对象,可用于存储数据值
* @param session
* 线程对象
*/
@RequestMapping("/admin/users/delete")
public String delete(@RequestParam(value = "id") String id,
@RequestParam(value = "page", defaultValue = "1") String page,
Model model,
HttpSession session) {
//创建数据库操作线程
Session db_session = DbConnection.getSession();
try{
//参数预处理
Integer currentPage = Integer.valueOf(page);
Integer userId = Integer.valueOf(id);
//进行删除操作
//创建初始条件
Criteria criteria = db_session.createCriteria(UsersEntity.class);
//往条件里加东西,等同于 where `id` = userId
criteria.add(Restrictions.eq("id", userId));
//只返回一条结果就好
criteria.setMaxResults(1);
//列出所有查询结果
List<UsersEntity> list = criteria.list();
UsersEntity user = list.get(0);
Transaction db_trans = db_session.beginTransaction();
db_session.delete(user);
db_trans.commit();
//返回信息
session.setAttribute("msg", "ID:" + id + "删除成功!");
return "redirect:/admin/users?page=" + currentPage;
}catch(Exception e) {
//添加错误信息
e.printStackTrace();
model.addAttribute("error_msg", " 系统发生了错误!");
return "admin/fail";
}finally {
//用完这个 数据库的 Session 记得关了
db_session.close();
}
}
/**
* @RequestParam注解的作用是:根据参数名从URL中取得参数值
* @param id
* 用户 id
* @param page
* 当前页数
* @param model
* 一个域对象,可用于存储数据值
*/
@RequestMapping(value = "/admin/users/edit", method = RequestMethod.GET)
public String edit_show(@RequestParam(value = "id") String id,
@RequestParam(value = "page", defaultValue = "1") String page,
Model model) {
//创建数据库操作线程
Session db_session = DbConnection.getSession();
try{
//参数预处理
Integer currentPage = Integer.valueOf(page);
Integer userId = Integer.valueOf(id);
//创建初始条件
Criteria criteria = db_session.createCriteria(UsersEntity.class);
//往条件里加东西,等同于 where `id` = userId
criteria.add(Restrictions.eq("id", userId));
//只返回一条结果就好
criteria.setMaxResults(1);
//列出所有查询结果
List<UsersEntity> list = criteria.list();
UsersEntity user = list.get(0);
//给管理页面加上要编辑的用户信息
model.addAttribute("User", user);
return "admin/users/edit";
}catch(Exception e) {
//添加错误信息
e.printStackTrace();
model.addAttribute("error_msg", " 系统发生了错误!");
return "admin/fail";
}finally {
//用完这个 数据库的 Session 记得关了
db_session.close();
}
}
/**
* @RequestParam注解的作用是:根据参数名从URL中取得参数值
* @param id
* 用户 id
* @param page
* 当前页数
* @param username
* 用户名
* @param password
* 密码
* @param user_role_type
* 当前页数
* @param model
* 一个域对象,可用于存储数据值
* @param session
* 线程对象
*/
@RequestMapping(value = "/admin/users/edit", method = RequestMethod.POST)
public String edit(@RequestParam(value = "id") String id,
@RequestParam(value = "page", defaultValue = "1") String page,
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password,
@RequestParam(value = "user_role_type") String user_role_type,
Model model,
HttpSession session) {
//创建数据库操作线程
Session db_session = DbConnection.getSession();
try{
//参数预处理
Integer currentPage = Integer.valueOf(page);
Integer userId = Integer.valueOf(id);
Byte userRoleType = Byte.valueOf(user_role_type);
//输入参数为空
if(username.equals("") || password.equals("")) {
//返回 错误信息
session.setAttribute("msg", "ID:" + id + " 编辑失败,参数不足!");
return "redirect:/admin/users?page=" + currentPage;
}
//创建初始条件
Criteria criteria = db_session.createCriteria(UsersEntity.class);
//往条件里加东西,等同于 where `id` = userId
criteria.add(Restrictions.eq("id", userId));
//只返回一条结果就好
criteria.setMaxResults(1);
//列出所有查询结果
List<UsersEntity> list = criteria.list();
UsersEntity user = list.get(0);
//创建事务,编辑,保存,提交事务
Transaction db_trans = db_session.beginTransaction();
user.setUsername(username);
user.setPassword(password);
user.setUserRoleType(userRoleType);
db_session.update(user);
db_trans.commit();
//返回信息
session.setAttribute("msg", "ID:" + id + " 编辑成功!");
return "redirect:/admin/users?page=" + currentPage;
}catch(Exception e) {
//添加错误信息
e.printStackTrace();
model.addAttribute("error_msg", " 系统发生了错误!");
return "admin/fail";
}finally {
//用完这个 数据库的 Session 记得关了
db_session.close();
}
}
/**
* @RequestParam注解的作用是:根据参数名从URL中取得参数值
* @param page
* 当前页数
* @param model
* 一个域对象,可用于存储数据值
*/
@RequestMapping(value = "/admin/users/add", method = RequestMethod.GET)
public String add_show(@RequestParam(value = "page", defaultValue = "1") String page,
Model model) {
try{
//参数预处理
Integer currentPage = Integer.valueOf(page);
return "admin/users/add";
}catch(Exception e) {
//添加错误信息
e.printStackTrace();
model.addAttribute("error_msg", " 系统发生了错误!");
return "admin/fail";
}
}
/**
* @RequestParam注解的作用是:根据参数名从URL中取得参数值
* @param page
* 当前页数
* @param username
* 用户名
* @param password
* 密码
* @param user_role_type
* 当前页数
* @param model
* 一个域对象,可用于存储数据值
* @param session
* 线程对象
*/
@RequestMapping(value = "/admin/users/add", method = RequestMethod.POST)
public String add(@RequestParam(value = "page", defaultValue = "1") String page,
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password,
@RequestParam(value = "user_role_type") String user_role_type,
Model model,
HttpSession session) {
//创建数据库操作线程
Session db_session = DbConnection.getSession();
try{
//参数预处理
Integer currentPage = Integer.valueOf(page);
Byte userRoleType = Byte.valueOf(user_role_type);
//输入参数为空
if(username.equals("") || password.equals("")) {
//返回 错误信息
session.setAttribute("msg", "添加失败,参数不足!");
return "redirect:/admin/users?page=" + currentPage;
}
//创建事务,编辑,保存,提交事务
Transaction db_trans = db_session.beginTransaction();
UsersEntity new_user = new UsersEntity();
new_user.setUsername(username);
new_user.setPassword(password);
new_user.setUserRoleType(userRoleType);
db_session.save(new_user);
db_trans.commit();
//返回信息
session.setAttribute("msg", "添加成功!");
return "redirect:/admin/users?page=" + currentPage;
}catch(Exception e) {
//添加错误信息
e.printStackTrace();
model.addAttribute("error_msg", " 系统发生了错误!");
return "admin/fail";
}finally {
//用完这个 数据库的 Session 记得关了
db_session.close();
}
}
}
4、运行,测试。






总结:
到这里我们的教程就到一段落了,希望大家能够理解每一个操作,每一行代码是什么意思。
上面其实也有很多不足的地方,比如创建查询的条件的时候那个方法是过时的方法,更合适的方法在这
https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/querycriteria.html
再比如,上面的查询和分页的那段代码应该增强复用性。
再比如从命名到注释,都得规范化,研究下 IDEA 的模板。
加油吧。

2 个评论
违和
大。。大佬。能否和小站换个友链,非常感谢!
网站名:违和
地址:https://vrhhe.pw
已在vrhhe.pw/links加了大佬的友链
glzjin
已添加