JAVAEE综合实验--新闻管理系统
新闻管理系统文章目录新闻管理系统一、用户管理模块1. 登录校验过滤器2. 用户注册3.用户登录4. 用户信息管理界面5. 用户信息修改6. 用户删除7. 用户审核8. 用户相关service9. 用户相关Dao效果图一、用户管理模块1. 登录校验过滤器@WebFilter("/*")public class LoginFilter implements Filter {@Overridepubli
·
新闻管理系统
文章目录
效果图
一、用户管理模块
1. 登录校验过滤器
@WebFilter("/*")
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//0.强制转换
HttpServletRequest request = (HttpServletRequest) req;
//1.获取资源请求路径
String uri = request.getRequestURI();
//2.判断是否包含登录相关资源路径,要注意排除掉 css/js/图片/验证码等资源
if(uri.contains("/index.jsp") || uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/add.jsp") || uri.contains("/img/") ){
//包含,主页不用登陆 用户就是想登录。放行
chain.doFilter(req, resp);
}else{
//不包含,需要验证用户是否登录
//3.从获取session中获取user
Object user = request.getSession().getAttribute("user");
if(user != null){
//登录了。放行
chain.doFilter(req, resp);
}else{
//没有登录。跳转登录页面
request.setAttribute("login_msg","您尚未登录,请登录");
request.getRequestDispatcher("/login.jsp").forward(request,resp);
}
}
}
@Override
public void init(FilterConfig config) throws ServletException {
}
@Override
public void destroy() {
}
}
2. 用户注册
- 效果图
- 页面jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>用户注册</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<%
//省份
String[] provinces = new String[]{
"河北","山西","辽宁","吉林","黑龙江","江苏","浙江","安徽",
"福建","江西","山东","河南","湖北","湖南","广东","海南",
"四川","贵州","云南","陕西","甘肃","青海","台湾",
"内蒙古","广西","西藏","宁夏","新疆",
"北京","上海","天津","重庆",
"香港","澳门"
};
request.setAttribute("provinces",provinces);
%>
<div class="container">
<center><h3>用户注册</h3></center>
<form action="${pageContext.request.contextPath}/addUserServlet" method="post">
<div class="form-group">
<label for="username">用户名:</label>
<input type="text" class="form-control" id="username" name="username" placeholder="请输入呢称">
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
</div>
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入真实姓名">
</div>
<div class="form-group">
<label>性别:</label>
<input type="radio" name="gender" value="男" checked="checked"/>男
<input type="radio" name="gender" value="女"/>女
</div>
<div class="form-group">
<label for="age">生日:</label>
<input type="text" class="form-control" id="age" name="birthday" placeholder="请输入生日,如:1998-09-21">
</div>
<div class="form-group">
<label for="address">籍贯:</label>
<select name="hometown" id="address" class="form-control" >
<c:forEach items="${provinces}" var="province">
<option value=${province}>${province}</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label for="hobby">爱好:</label>
<input type="text" class="form-control" name="hobby" id="hobby" placeholder="请输入你的爱好"/>
</div>
<div class="form-group">
<label for="introduction">简介:</label>
<input type="text" class="form-control" name="introduction" id="introduction" placeholder="让我们多了解你"/>
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" />
<a class="btn btn-default" href="javascript:history.back(-1)">返回</a>
</div>
</form>
</div>
</body>
</html>
- sevlet 实现
@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置字符编码
request.setCharacterEncoding("utf-8");
//2.获取表单数据
Map<String, String[]> map = request.getParameterMap();
//3.数据封装
User user = new User();
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//3.1补充表单没有的数据
UserService service = new UserServiceImp();
//判断是否是第一个注册
//如果是 则为管理员 否则 为普通成员
if (service.countUser() > 1) {
user.setCasting(0);
} else {
user.setCasting(1);
}
//注册时间设置
user.setRegisterTime(this.getRegisterTime());
//4.service完成成员注册
service.insertUser(user);
//5.注册成功 转发到登录页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* 获取注册时间
* */
private String getRegisterTime() {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
return simpleDateFormat.format(new Date());
}
}
3.用户登录
- 效果图
- 前端jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>用户登录</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">用户登录</h3>
<form action="${pageContext.request.contextPath}/loginServlet" method="post">
<div class="form-group">
<label for="user">用户名:</label>
<input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/>
</div>
<div class="form-group">
<label for="password">密码:</label>
<input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
</div>
<div class="form-group" style="text-align: center;">
<input class="btn btn btn-primary" type="submit" value="登录">
<a href="${pageContext.request.contextPath}/add.jsp" class="btn btn btn-primary">注册</a>
</div>
</form>
<!-- 出错显示的信息框 -->
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert">
<span>×</span></button>
<strong>${login_msg}</strong>
</div>
</div>
</body>
</html>
- servlet实现
/**
* @author iforeverhz
*/
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.设置编码
req.setCharacterEncoding("utf-8");
//2.获得所有请求参数
Map<String, String[]> map = req.getParameterMap();
//3.1封装User对象
User loginUser = new User();
try {
BeanUtils.populate(loginUser, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//4.调用UserService 查询
UserService service = new UserServiceImp();
User user = service.login(loginUser);
//5.判断用户是否注册 根据情况进行请求转发
if (user == null) {
//登录失败
req.setAttribute("login_msg", "用户名或密码错误!");
//转发到登录页面
req.getRequestDispatcher("/login.jsp").forward(req, resp);
} else if (user.getEntry() == 0) {
//登录失败 注册但还未审核
req.setAttribute("login_msg", "您的注册还在审核中,请稍等!");
//转发到登录页面
req.getRequestDispatcher("/login.jsp").forward(req, resp);
} else if (user.getCasting() == 1) {
//存储数据
req.getSession().setAttribute("user", user);
//登录成功 管理员 重复定到管理界面
//resp.sendRedirect(req.getContextPath() + "/findUserByPageServlet");
resp.sendRedirect(req.getContextPath() + "/index.jsp");
} else {
//存储数据
req.getSession().setAttribute("user", user);
//登录成功 返回首页
resp.sendRedirect(req.getContextPath() + "/index.jsp");
}
}
}
4. 用户信息管理界面
- 效果图
- 前端jsp
<%@ page import="java.util.List" %>
<%@ page import="com.hky.pojo.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>用户信息管理系统</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
<style type="text/css">
td, th {
text-align: center;
}
.company {
height: 40px;
background-color: #ffc900;
text-align: center; /*水平居中*/
line-height: 40px; /*垂直居中*/
size: 8px;
}
html, body {
margin: 0;
padding: 0;
}
.container {
min-height: 100%;
}
main {
padding-bottom: 100px;
}
/* main的padding-bottom值要等于或大于footer的height值 */
footer {
height: 100px;
margin-top: -100px;
}
/* margin-top(负值的)高度等于footer的height值 */
</style>
</head>
<body>
<div class="container">
<header class="">
<div class="row">
<img src="img/top.png" class="img-responsive" style="width: 100% ;height: auto">
</div>
<div class="row">
<!--页眉-->
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.jsp">首页</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet">用户管理
<span class="sr-only">(current)</span></a></li>
<li><a href="${pageContext.request.contextPath}/findNewsByPageServlet">新闻管理</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
aria-haspopup="true"
aria-expanded="false">当前用户:${pageContext.session.getAttribute("user").username} <span
class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="${pageContext.request.contextPath}/logoutServlet">退出登录</a></li>
<li role="separator" class="divider"></li>
<li>
<a href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改信息</a>
</li>
<li role="separator" class="divider"></li>
</ul>
</li>
<li><a class="navbar-brand " href="${pageContext.request.contextPath}/login.jsp">登录</a></li>
<li><a class="navbar-brand " href="${pageContext.request.contextPath}/add.jsp">注册</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
</header>
<main>
<div class="">
<h3 style="text-align: center">用户信息列表</h3>
<div style="float: left">
<form class="form-inline"
action="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${ pb.currentPage -1}&rows=8"
method="post">
<div class="form-group">
<label for="exampleInputName2">用户名</label>
<input type="text" class="form-control" name="username" value="${condition.username[0]}"
id="exampleInputName2">
</div>
<div class="form-group">
<label for="exampleInputEmail2">籍贯</label>
<input type="text" class="form-control" name="hometown" value="${condition.hometown[0]}"
id="exampleInputEmail2">
</div>
<div class="form-group">
<label for="exampleInputEmail">性别</label>
<input type="text" class="form-control" name="gender" value="${condition.gender[0]}"
id="exampleInputEmail">
</div>
<button type="submit" class="btn btn-default">查询</button>
</form>
</div>
<%-- <div style="float: right; margin: 5px">--%>
<%-- <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a>--%>
<%-- </div>--%>
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th>编号</th>
<th>用户名</th>
<th>密码</th>
<th>姓名</th>
<th>性别</th>
<th>出生日期</th>
<th>籍贯</th>
<th>爱好</th>
<th>简介</th>
<th>注册时间</th>
<th>是否审核</th>
<th>操作</th>
</tr>
<c:forEach items="${pb.list}" var="user" varStatus="s">
<tr>
<td>${s.count}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.birthday}</td>
<td>${user.hometown}</td>
<td>${user.hobby}</td>
<td>${user.introduction}</td>
<td>${user.registerTime}</td>
<td>${user.entry == 0 ? "否":"是"} </td>
<td>
<a class="btn btn-default btn-sm"
href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a>
<a class="btn btn-default btn-sm"
href="${pageContext.request.contextPath}/delUserServlet?id=${user.id}">删除</a>
<a class="btn btn-default btn-sm"
href="${pageContext.request.contextPath}/entryUserServlet?id=${user.id}">审核通过</a>
</td>
</tr>
</c:forEach>
</table>
<div>
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${pb.currentPage == 1}">
<li class="disabled">
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${ pb.currentPage -1}&rows=8&username=${condition.username[0]}&hometown=${condition.hometown[0]}&gender=${condition.gender[0]}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:if test="${pb.currentPage != 1}">
<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${ pb.currentPage -1}&rows=8&username=${condition.username[0]}&hometown=${condition.hometown[0]}&gender=${condition.gender[0]}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach begin="1" end="${pb.totalPage}" var="i">
<c:if test="${pb.currentPage == i}">
<li class="active"><a
href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=8&username=${condition.username[0]}&hometown=${condition.hometown[0]}&gender=${condition.gender[0]}">${i}</a>
</li>
</c:if>
<c:if test="${ pb.currentPage != i}">
<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=8&username=${condition.username[0]}&hometown=${condition.hometown[0]}&gender=${condition.gender[0]}">${i}</a>
</li>
</c:if>
</c:forEach>
<c:if test="${pb.currentPage == pb.totalPage }">
<li class="disabled">
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${ pb.currentPage +1}&rows=8&username=${condition.username[0]}&hometown=${condition.hometown[0]}&gender=${condition.gender[0]}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<c:if test="${pb.currentPage != pb.totalPage }">
<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${ pb.currentPage +1}&rows=8&username=${condition.username[0]}&hometown=${condition.hometown[0]}&gender=${condition.gender[0]}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<span style="font-size: 25px; margin: 15px">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>
</ul>
</nav>
</div>
</div>
</main>
</div>
<!--页脚部分-->
<footer class="container">
<div class="row company">
Copyright @2018-2022 Iforeverhz 在线新闻系统 版权所有 | 联系热线:408888888
</div>
</footer>
</body>
</html>
5. 用户信息修改
思路:管理页面点击修改按钮->后台根据用户id查询信息(findUserServlet),转发到用户信息更新页面(update.jsp),数据回显->修改信息,点击提交(updateUserServlet)
- 效果图
- servlet设计
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取id
String id = request.getParameter("id");
//2.调用service
UserService service = new UserServiceImp();
User user = service.findUser(id);
//3.转发到update.jsp
request.setAttribute("user", user);
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
@WebServlet("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置字符编码
request.setCharacterEncoding("utf-8");
//2.疯转表单对象
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//3.调用修改用户服务 修改用户信息
UserService service = new UserServiceImp();
service.updateUser(user);
//4.重定向 用户管理界面
response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
6. 用户删除
@WebServlet("/delUserServlet")
public class DelUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取删除用户的id
String id = request.getParameter("id");
//2.调用service 删除user
UserService service = new UserServiceImp();
service.delUserById(id);
//3.重定向到list.jsp
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
7. 用户审核
@WebServlet("/entryUserServlet")
public class EntryUserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取删除用户的id
String id = request.getParameter("id");
//2.调用service 删除user
UserService service = new UserServiceImp();
service.passEntry(id);
//3.重定向到list.jsp
response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
8. 用户相关service
- 接口定
/**
* @author iforeverhz
*/
public interface UserService {
/**
* 查找全部用户信息
*
* @return List<User>
*/
public List<User> findAll();
/**
* 用户登录校验
*
* @param user user对象
* @return User
*/
public User login(User user);
/**
* 用户新增
*
* @param user user对象
*/
public void insertUser(User user);
/**
* 查询表中用户的的数量
*
* @return int
*/
public int countUser();
/**
* 根据id删除用户
*
* @param id id
*/
public void delUserById(String id);
/**
* 查询用户
*
* @param id
* @return User
*/
public User findUser(String id);
/**
* 更新用户信息
*
* @param user
*/
public void updateUser(User user);
/**
* 分页条件查询
*
* @param currentPage
* @param rows
* @param condition
* @return
*/
public PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition);
/**
* 管理员审核其他用户
* @param id
*/
public void passEntry(String id);
}
- 实现类
/**
* @author iforeverhz
*/
public class UserServiceImp implements UserService {
UserDao userDao = new UserDaoImp();
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public User login(User user) {
return userDao.findUserByUsernameAndPassword(user.getUsername(), user.getPassword());
}
@Override
public void insertUser(User user) {
userDao.insertUser(user);
}
@Override
public int countUser() {
return userDao.countUser();
}
@Override
public void delUserById(String id) {
userDao.delUserById(Integer.parseInt(id));
}
@Override
public User findUser(String id) {
return userDao.findUserById(Integer.parseInt(id));
}
@Override
public void updateUser(User user) {
userDao.update(user);
}
@Override
public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
//1.创建PageBean
PageBean<User> pageBean = new PageBean<>();
//2.数据类型转换
int currentPage = Integer.parseInt(_currentPage);
int rows = Integer.parseInt(_rows);
//3.查询数据总数
int totalCount = userDao.findTotalCount(condition);
pageBean.setTotalCount(totalCount);
//4.总页码计算
int totalPage = totalCount % rows == 0 ? (totalCount / rows) : (totalCount / rows + 1);
pageBean.setTotalPage(totalPage);
//5.对当前页数进行限制
if (currentPage <= 0) {
currentPage = 1;
}else if (currentPage >= totalPage) {
currentPage = totalPage;
}
pageBean.setCurrentPage(currentPage);
pageBean.setRows(rows);
//6.分页查询数据
int start = (currentPage - 1) * rows;
List<User> users = userDao.findByPage(start, rows, condition);
pageBean.setList(users);
return pageBean;
}
@Override
public void passEntry(String id) {
if (id != null ||"".equals(id)){
int uid = Integer.parseInt(id);
userDao.updateEntry(uid);
}
}
}
9. 用户相关Dao
- 接口定义
public interface UserDao {
/**
* 查询所有用户
*
* @return User对象
*/
public List<User> findAll();
/**
* 通过用户名和密码查询用户
*
* @param username 用户名
* @param password 用户密码
* @return User对象
*/
public User findUserByUsernameAndPassword(String username, String password);
/**
* 统计User表用户数量
*
* @return int 用户数量
*/
public int countUser();
/**
* 用户注册
*
* @return 无
*/
public void insertUser(User user);
/**
* 根据id删除用户
*
* @param id
*/
public void delUserById(int id);
/**
* 根据id查找用户
*
* @param id
* @return User
*/
public User findUserById(int id);
/**
* @param user
*/
public void update(User user);
/**
* 分页查询总数
*
* @param condition
* @return
*/
public int findTotalCount(Map<String, String[]> condition);
/**
* 分页查询数据
*
* @param start
* @param rows
* @param condition
* @return
*/
public List<User> findByPage(int start, int rows, Map<String, String[]> condition);
/**
* 修改 entry值
* @param uid
*/
public void updateEntry(int uid);
}
- 接口实现
public class UserDaoImp implements UserDao {
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public List<User> findAll() {
String sql = "select * from `user`";
List<User> users = template.query(sql, new BeanPropertyRowMapper<>(User.class));
return users;
}
@Override
public User findUserByUsernameAndPassword(String username, String password) {
try {
String sql = "select * from `user` where username = ? and password = ? ";
User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username, password);
return user;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public int countUser() {
String sql = "select count(id) from `user`";
Integer count = template.queryForObject(sql, Integer.class);
return count;
}
@Override
public void insertUser(User user) {
String sql = "insert into `user` values(?,?,?,?,?,?,?,?,?,?,?,?)";
Object[] obj = new Object[]{
null, user.getUsername(), user.getPassword(), user.getName(), user.getGender(), user.getBirthday(), user.getHometown(),
user.getHobby(), user.getIntroduction(), user.getCasting(), user.getRegisterTime(), 0
};
int i = template.update(sql, obj);
}
@Override
public void delUserById(int id) {
String sql = "delete from `user` where id = ? ";
template.update(sql, id);
}
@Override
public User findUserById(int id) {
String sql = "select * from `user` where id =?";
User user = template.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
if (user != null) {
return user;
} else {
return null;
}
}
@Override
public void update(User user) {
String sql = "update `user` set `password` = ? ,`name` = ?, gender = ? ,birthday = ?,hometown = ?, hobby = ? ,introduction = ? where id = ?";
Object[] args = new Object[]{
user.getPassword(), user.getName(), user.getGender(), user.getBirthday(),
user.getHometown(), user.getHobby(), user.getIntroduction(), user.getId()
};
template.update(sql, args);
}
@Override
public int findTotalCount(Map<String, String[]> condition) {
//1.定义模班
String sql = "select count(*) from `user` where 1 = 1 ";
//2.动态拼接sql
StringBuilder stringBuilder = new StringBuilder(sql);
//3.定义参数集合
List<Object> params = new ArrayList<>();
//4.遍历map
Set<String> keySet = condition.keySet();
for (String key : keySet) {
//排除分页条件参数
if ("currentPage".equals(key) || "rows".equals(key)) {
continue;
}
//获得value
String value = condition.get(key)[0];
if (value != null || !"".equals(value)) {
//查询条件有值
stringBuilder.append(" and " + key + " like ? ");
//占位符的值
params.add("%" + value + "%");
}
}
return template.queryForObject(stringBuilder.toString(), Integer.class, params.toArray());
}
@Override
public List<User> findByPage(int start, int rows, Map<String, String[]> condition) {
//1.sql模版
String sql = "select * from `user` where 1 = 1 ";
//2.动态拼接sql
StringBuilder stringBuilder = new StringBuilder(sql);
//3.定义参数集合
List<Object> params = new ArrayList<>();
//4.遍历map
Set<String> keySet = condition.keySet();
for (String key : keySet) {
//排除分页条件参数
if ("currentPage".equals(key) || "rows".equals(key)) {
continue;
}
//获得value
String value = condition.get(key)[0];
if (value != null || !"".equals(value)) {
//查询条件有值
stringBuilder.append(" and " + key + " like ? ");
//占位符的值
params.add("%" + value + "%");
}
}
//5.添加分页查询条件
stringBuilder.append(" limit ?,?");
//6.添加分页查询参数
params.add(start);
params.add(rows);
List<User> users = template.query(stringBuilder.toString(), new BeanPropertyRowMapper<>(User.class), params.toArray());
return users;
}
@Override
public void updateEntry(int uid) {
String sql = "update `user` set entry = ? where id = ?";
template.update(sql, 1, uid);
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)