目录
一、简单功能
1.列表查询
2.登录
3.添加
4.删除
5.修改
二、复杂功能
1.删除选中
2.分页查询
3.模糊条件查询
一、简单功能
1.列表查询
2.登录
2.1 login.jsp代码
<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-inline">
<label for="vcode">验证码:</label>
<input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/>
<a href="javascript:refreshCode()">
<img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/></a>
</div>
<hr/>
<div class="form-group" style="text-align: center;">
<input class="btn btn btn-primary" type="submit" value="登录">
</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>
点击登录后会自动提交到LoginServlet中
?2.2 loginServlet
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取数据
//2.1获取用户填写验证码
String code = request.getParameter("verifycode");
//3.验证码校验
HttpSession session = request.getSession();
String verify = (String) session.getAttribute("CHECK_CODE_SERVER");
session.removeAttribute("CHECK_CODE_SERVER");//确保验证码一致性
if (!verify.equalsIgnoreCase(code)) {
//验证码不正确
//提示信息
request.setAttribute("login_msg", "您输入的验证码错误,请重新输入!!");
//跳转登陆界面
request.getRequestDispatcher("/login.jsp").forward(request, response);
return;
}
Map<String, String[]> map = request.getParameterMap();
//4.封装User对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//5.调用Service查询
UserService service = new UserServiceImpl();
User loginUser = service.login(user);
//6.判断是否登录成功
if(loginUser != null){
//登录成功
//将用户存入session
session.setAttribute("user",loginUser);
//跳转页面
response.sendRedirect(request.getContextPath()+"/index.jsp");
}else{
//登录失败
//提示信息
request.setAttribute("login_msg","用户名或密码错误!");
//跳转登录页面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
进入LoginServlet后会对验证码进行校验,如果验证码出错,会返回到login.jsp并且提示验证码出错。如果验证码正确,会调用service中的login方法获取user对象。如果用户或密码错误,则user对象为空,会返回到login.jsp并且提示用户或密码出错。正确则会将user存到session中,方便之后使用,并且跳转到下一页面。
3.添加
4.删除
?在使用删除功能时,为避免用户误删,可以在用户点击删除按钮时,弹出确认删除按钮
function deleteUser(id) {
if (confirm("你确定要删除吗?")) {
location.href = "${pageContext.request.contextPath}/deleteServlet?id=" + id;
}
}
5.修改
?修改用户信息需要完成数据的回显,方便用户修改信息
5.1 findUserServlet
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取id
String id = request.getParameter("id");
//2.调用service查询
UserServiceImpl userService = new UserServiceImpl();
User userById = userService.findUserById(id);
//3.将user存入request
request.setAttribute("user",userById);
//4.转发到update.jsp
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
?5.2 update.jsp
设置一个隐藏域,获取Id
<%--这是一个隐藏域--%>
<input type="hidden" name="id" value="${user.id}">
?5.3 updateUserServlet
@WebServlet("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取Map
Map<String, String[]> parameterMap = request.getParameterMap();
//3.封装对象
User user = new User();
try {
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//4.调用Service修改
UserServiceImpl userService = new UserServiceImpl();
userService.updateUserById(user);
//5.跳转到查询所有Servlet
response.sendRedirect(request.getContextPath()+"/userByPageServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
二、复杂功能
1.删除选中
可以删除勾选,一次删除多条数据。
?
?
?
<script>
window.onload = function () {
//给删除选中按钮添加单击事件
document.getElementById("delSelected").onclick = function () {
if (confirm("你确定要删除选中条目吗?")) {
var flag = false;
//判断是否有选中条目
var cbs = document.getElementsByName("uid");
for (var i = 0; i < cbs.length; i++) {
if (cbs[i].checked) {
flag = true;
break;
}
}
if (flag) {
document.getElementById("form").submit();
}
}
}
document.getElementById("firstCh").onclick = function () {
var cbs = document.getElementsByName("uid");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = this.checked;
}
}
}
</script>
? <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中</a>
</div>
<form id="form" action="${pageContext.request.contextPath}/delSelectServlet" method="post">
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th><input type="checkbox" id="firstCh"></th>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>籍贯</th>
<th>QQ</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<c:forEach items="${pb.list}" var="user" varStatus="s">
<tr>
<td><input type="checkbox" name="uid" value="${user.id}"></td>
<td>${s.count}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
<td>${user.age}</td>
<td>${user.address}</td>
<td>${user.qq}</td>
<td>${user.email}</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="javascript:deleteUser(${user.id});">删除</a></td>
</tr>
</c:forEach>
</table>
</form>
?
DelSelectedServlet代码
@WebServlet("/delSelectServlet")
public class DelSelectServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取所有的id
String[] ids = request.getParameterValues("uid");
//2.调用service删除
UserServiceImpl userService = new UserServiceImpl();
userService.delSelectedUser(ids);
//3.跳转到查询所有的Servlet
response.sendRedirect(request.getContextPath()+"/userByPageServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
service代码(重复调用之前所写的删除单个用户的方法):
public void delSelectedUser(String[] ids) {
//遍历数组
if (ids.length > 0) {
for (String s : ids) {
//调用dao删除
dao.deleteUserById(Integer.parseInt(s));
}
}
}
2.分页查询
?在我们读取数据库中的数据时,往往会因为数据量过大无法在一个页面中完整显示,使用分页操作,可以使界面简洁,条理清晰。
?
首先创建Page实体类,保存数据
public class Page<T> {
private int totalCount;//总的记录数
private int totalPage; //总页码
private List<T> list; //每页的数据
private int currentPage; //当前页码
private int rows; //每页显示的记录数
......
}
?在jsp中写分页功能
<div>
<nav>
<ul class="pagination">
<c:if test="${pb.currentPage == 1}">
<li class="disabled">
</c:if>
<c:if test="${pb.currentPage != 1}">
<li>
</c:if>
<a href="${pageContext.request.contextPath}/userByPageServlet?currentPage=${pb.currentPage-1}&rows=5&name=${map.name[0]}&address=${map.address[0]}&email =${map.email[0]}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<c:forEach begin="1" end="${pb.totalPage}" var="i">
<c:if test="${pb.currentPage==i}">
<li class="active"><a
href="${pageContext.request.contextPath}/userByPageServlet?currentPage=${i}&rows=5&name=${map.name[0]}&address=${map.address[0]}&email =${map.email[0]}">${i}</a>
</li>
</c:if>
<c:if test="${pb.currentPage!=i}">
<li>
<a href="${pageContext.request.contextPath}/userByPageServlet?currentPage=${i}&rows=5&name=${map.name[0]}&address=${map.address[0]}&email =${map.email[0]}">${i}</a>
</li>
</c:if>
</c:forEach>
<c:if test="${pb.currentPage == pb.totalPage}">
<li class="disabled">
</c:if>
<c:if test="${pb.currentPage != pb.totalPage}">
<li>
</c:if>
<c:if test="${pb.currentPage != pb.totalPage}">
<a href="${pageContext.request.contextPath}/userByPageServlet?currentPage=${pb.currentPage+1}&rows=5&name=${map.name[0]}&address=${map.address[0]}&email =${map.email[0]}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</c:if>
<c:if test="${pb.currentPage == pb.totalPage}">
<a href="${pageContext.request.contextPath}/userByPageServlet?currentPage=${pb.currentPage}&rows=5&name=${map.name[0]}&address=${map.address[0]}&email =${map.email[0]}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</c:if>
</li>
<span style="font-size: 25px;margin-left: 5px">
共${pb.totalCount}条记录,${pb.totalPage}页
</span>
</ul>
</nav>
</div>
UserByPageServlet
@WebServlet("/userByPageServlet")
public class UserByPageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1.获取参数:当前页码:currentPage,每页显示条数:rows
String currentPage = request.getParameter("currentPage");
String rows = request.getParameter("rows");
if (currentPage == null || "".equals(currentPage)) {
currentPage = "1";
}
if (rows == null || "".equals(rows)) {
rows = "5";
}
//获取条件查询参数
Map<String, String[]> map = request.getParameterMap();
//2.调用service查询
UserServiceImpl userService = new UserServiceImpl();
Page<User> pb = userService.userByPage(currentPage, rows, map);
//3.将Page对象存入request
request.setAttribute("pb", pb);
request.setAttribute("map",map);//将查询条件存入request
//4.转发到list.jsp
request.getRequestDispatcher("/list.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
分页Service
public Page<User> userByPage(String currentPages, String rows, Map<String, String[]> map) {
int currentPage = Integer.parseInt(currentPages);
int row = Integer.parseInt(rows);
if (currentPage <= 0) {
currentPage = 1;
}
//1.创建空的Page对象
Page<User> pb = new Page<User>();
//2.设置当前页面属性rows属性
pb.setCurrentPage(currentPage);
pb.setRows(row);
//3.调用dao查询totalCount总记录数
int count = dao.getTotalCount(map);
pb.setTotalCount(count);
//4.调用dao查询list集合
//计算开始的记录索引
int start = (currentPage - 1) * row;
List<User> list = dao.findByPage(start, row,map);
pb.setList(list);
//5.计算总页码
int totalPage = count % row == 0 ? count / row : (count / row) + 1;
pb.setTotalPage(totalPage);
//6.返回page对象
return pb;
}
DAO
public List<User> findByPage(int start, int rows, Map<String, String[]> map) {
String sql = "select * from user where 1=1";
StringBuilder sb = new StringBuilder(sql);
//遍历Map集合
Set<String> set = map.keySet();
//定义一个放参数的集合
List<Object> params = new ArrayList<Object>();
for (String key : set) {
String value = map.get(key)[0];
//判断Value是否有值
if (value != null && !"".equals(value)) {
//排除分页条件参数
if ("currentPage".equals(key) || "rows".equals(key)) {
continue;
}
sb.append(" and " + key + " like ? ");
params.add("%" + value + "%");//?条件的值
}
}
//添加条件查询
sb.append(" limit ? , ?");
//添加分页查询条件值
params.add(start);
params.add(rows);
sql = sb.toString();
return template.query(sql, new BeanPropertyRowMapper<User>(User.class), params.toArray());
}
@Override
public int getTotalCount(Map<String, String[]> map) {
//定义模板初始化SQL
String sql = "select count(*) from user where 1=1";
StringBuilder sb = new StringBuilder(sql);
//遍历Map集合
Set<String> set = map.keySet();
//定义一个放参数的集合
List<Object> params = new ArrayList<Object>();
for (String key : set) {
String value = map.get(key)[0];
//判断Value是否有值
if (value != null && !"".equals(value)) {
//排除分页条件参数
if ("currentPage".equals(key) || "rows".equals(key)) {
continue;
}
sb.append(" and " + key + " like ? ");
params.add("%" + value + "%");//?条件的值
}
}
return template.queryForObject(sb.toString(), Integer.class, params.toArray());
}
}
3.模糊条件查询
模糊查询和分页查询功能相差不多同样需要分页,在分页查询的service和dao包操作时已经进行了添加
?
<div style="float: left">
<form class="form-inline" action="${pageContext.request.contextPath}/userByPageServlet" method="post">
<div class="form-group">
<label for="exampleInputName2">姓名</label>
<input type="text" name="name" value="${map.name[0]}" class="form-control" id="exampleInputName2"
placeholder="请输入姓名">
</div>
<div class="form-group">
<label for="exampleInputAddress2">籍贯</label>
<input type="text" name="address" value="${map.address[0]}" class="form-control"
id="exampleInputAddress2" placeholder="请输入籍贯">
</div>
<div class="form-group">
<label for="exampleInputEmail2">邮箱</label>
<input type="text" name="email" value="${map.email[0]}" class="form-control" id="exampleInputEmail2"
placeholder="请输入邮箱">
</div>
<button type="submit" class="btn btn-default">查询</button>
</form>
</div>
|