一、简单功能
1.列表查询
2.登录
登录时要先校验验证码是否正确,再去校验账号密码,密码正确后将用户存入session。
前端代码:
<script type="text/javascript">
function refreshCode() {
var vcode=document.getElementById("vcode");
vcode.src="${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();
}
</script>
后端servlet代码:
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String verifycode = request.getParameter("verifycode");
HttpSession session = request.getSession();
String checkcode_server =(String) session .getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");
if(!checkcode_server.equalsIgnoreCase(verifycode)){
request.setAttribute("login_msg","验证码错误!");
request.getRequestDispatcher("/login.jsp").forward(request,response);
return;
}
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();
}
UserService service=new UserServiceImpl();
User loginUser =service.login(user);
if(loginUser !=null){
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);
}
}
测试结果: 用户名或密码错误 验证码错误 验证码,用户名和密码都输入正确后会进入下一个页面
3.添加
前端代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- HTML5文档-->
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<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>
<div class="container">
<center><h3>添加联系人页面</h3></center>
<form action="${pageContext.request.contextPath}/addUserServlet" method="post" id="form">
<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="age" placeholder="请输入年龄">
</div>
<div class="form-group">
<label for="address">籍贯:</label>
<select name="address" class="form-control" id="address">
<option value="陕西">陕西</option>
<option value="北京">北京</option>
<option value="上海">上海</option>
</select>
</div>
<div class="form-group">
<label for="qq">QQ:</label>
<input type="text" class="form-control" id="qq" name="qq" placeholder="请输入QQ号码"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email" name="email" 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="重置" />
<input class="btn btn-default" type="button" value="返回" />
</div>
</form>
</div>
</body>
</html>
后端代码:
@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
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();
}
UserService service=new UserServiceImpl();
service.addUser(user);
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
4.删除
删除信息时,给出提示,避免用户误删 前端代码:
function deleteUser(id) {
if(confirm("您确定要删除吗?")){
location.href="${pageContext.request.contextPath}/delUserServlet?id="+id;
}
}
后端代码:
@WebServlet("/delSelectedServlet")
public class DelSelectedServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] ids = request.getParameterValues("uid");
UserService service = new UserServiceImpl();
service.delSelectedUser(ids);
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
5.修改
修改用户信息要使数据能够回显信息,方便用户修改信息
前端代码:
设置隐藏域
<%--隐藏域 提交id--%>
<input type="hidden" name="id" value="${user.id}">
后端代码:
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id =request.getParameter("id");
UserService service = new UserServiceImpl();
User user = service.findUserById(id);
request.setAttribute("user",user);
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
@WebServlet("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
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();
}
UserService service = new UserServiceImpl();
service.updateUser(user);
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
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("firstCb").onclick = function () {
var cbs = document.getElementsByName("uid");
for(var i =0; i<cbs.length;i++){
cbs[i].checked = this.checked;
}
}
}
</script>
</head>
<body>
<div class="container">
<h3 style="text-align: center">用户信息列表</h3>
<div style="float: left;">
<form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
<div class="form-group">
<label for="exampleInputName2">姓名</label>
<input type="text" name="name" value="${condition.name[0]}" class="form-control" id="exampleInputName2" >
</div>
<div class="form-group">
<label for="exampleInputName3">籍贯</label>
<input type="text" name="address" value="${condition.address[0]}" class="form-control" id="exampleInputName3" >
</div>
<div class="form-group">
<label for="exampleInputEmail2">邮箱</label>
<input type="text" name="email" value="${condition.email[0]}" class="form-control" id="exampleInputEmail2" >
</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>
<a class="btn btn-primary" href="javascript:void(0);"id="delSelected">删除选中</a>
</div>
<form id="form" action="${pageContext.request.contextPath}/delSelectedServlet" method="post">
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th><input type="checkbox" id="firstCb"></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>
后端代码:
servlet代码:
@WebServlet("/delSelectedServlet")
public class DelSelectedServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] ids = request.getParameterValues("uid");
UserService service = new UserServiceImpl();
service.delSelectedUser(ids);
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
service代码:
public void delSelectedUser(String[] ids) {
if(ids != null && ids.length > 0){
for(String id :ids){
dao.delete(Integer.parseInt(id));
}
}
}
2.分页查询
将数据分页查询,可以减轻服务器的开销,提升了用户的体验。 先创建分页对象,pageBean实体类
public class PageBean<T> {
private int totalCount;
private int totalPage;
private List<T> list;
private int currentPage;
private int rows;
...
}
前端代码:
<div>
<nav aria-label="Page navigation">
<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}/findUserByPageServlet?currentPage=${pb.currentPage - 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.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}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage != i}">
<li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.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>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
<span style="font-size: 25px;margin-left:5px; ">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>
</ul>
</nav>
</div>
后端代码: servlet:
@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
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[]> condition = request.getParameterMap();
UserService service =new UserServiceImpl();
PageBean<User> pb = service.findUserByPage(currentPage,rows,condition);
System.out.println(pb);
request.setAttribute("pb",pb);
request.setAttribute("condition",condition);
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
service:
@Override
public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
int currentPage = Integer.parseInt(_currentPage);
int rows = Integer.parseInt(_rows);
if(currentPage <=0){
currentPage = 1;
}
PageBean<User> pb = new PageBean<User>();
int totalCount = dao.findTotalCount(condition);
pb.setTotalCount(totalCount);
int totalPage = totalCount % rows == 0 ? totalCount / rows : totalCount / rows + 1;
pb.setTotalPage(totalPage);
if (currentPage > totalPage) {
currentPage = totalPage;
}
pb.setCurrentPage(currentPage);
pb.setRows(rows);
int start = (currentPage - 1)*rows;
List<User> list =dao.findByPage(start,rows,condition);
pb.setList(list);
return pb;
}
3.复杂条件查询
前端代码:
<div style="float: left;">
<form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
<div class="form-group">
<label for="exampleInputName2">姓名</label>
<input type="text" name="name" value="${condition.name[0]}" class="form-control" id="exampleInputName2" >
</div>
<div class="form-group">
<label for="exampleInputName3">籍贯</label>
<input type="text" name="address" value="${condition.address[0]}" class="form-control" id="exampleInputName3" >
</div>
<div class="form-group">
<label for="exampleInputEmail2">邮箱</label>
<input type="text" name="email" value="${condition.email[0]}" class="form-control" id="exampleInputEmail2" >
</div>
<button type="submit" class="btn btn-default">查询</button>
</form>
</div>
|