一、登录
1.登录界面(JSP)
页面展示: JSP页面代码:
<%--
Created by IntelliJ IDEA.
User: zhang
Date: 2022/3/17
Time: 20:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<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>
<script type="text/javascript">
function refreshCode() {
let vcode = document.getElementById("vcode");
vcode.src="${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();
}
</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-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>
</body>
</html>
这一段内容是用于获取验证码,登录功能代码就很简单不解释了。
2.登录界面的servlet
package cn.itcast.web.servlet;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
import com.mysql.jdbc.EscapeTokenizer;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@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);
}
}
这是实现登录最核心的内容,用于传递客户端和服务器之间的数据。
二、添加功能
1.逻辑图
2.添加界面(JSP)
<%--
Created by IntelliJ IDEA.
User: zhang
Date: 2022/3/18
Time: 11:14
To change this template use File | Settings | File Templates.
--%>
<%@ 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">
<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="jiguan">
<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" name="qq" placeholder="请输入QQ号码"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" 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>
添加用户籍贯位置这里的代码不是普通的text类型了,而是改成了下拉列表框。
<div class="form-group">
<label for="address">籍贯:</label>
<select name="address" class="form-control" id="jiguan">
<option value="广东">广东</option>
<option value="广西">广西</option>
<option value="湖南">湖南</option>
</select>
</div>
里面的值可以根据需要进行修改。
3.添加界面的servlet
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");
三、删除功能
1.逻辑图
2.删除功能的servlet
String id = request.getParameter("id");
UserService service = new UserServiceImpl();
service.deleteUser(id);
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
将要删除的用户id信息传递到数据库处理Java类中进行操作。
四、修改功能
1.逻辑图
2.修改功能页面(JSP)
<%--
Created by IntelliJ IDEA.
User: zhang
Date: 2022/3/18
Time: 16:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>修改用户</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js"></script>
<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}/updateUserServlet" method="post">
<%-- 隐藏域来提交id--%>
<input type="hidden" name="id" value="${user.id}">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" value="${user.name}" readonly="readonly" placeholder="请输入姓名" />
</div>
<div class="form-group">
<label>性别:</label>
<c:if test="${user.gender=='男'}">
<input type="radio" name="gender" value="男" checked />男
<input type="radio" name="gender" value="女" />女
</c:if>
<c:if test="${user.gender=='女'}">
<input type="radio" name="gender" value="男" />男
<input type="radio" name="gender" value="女" checked />女
</c:if>
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="text" class="form-control" id="age" name="age" value="${user.age}" placeholder="请输入年龄" />
</div>
<div class="form-group">
<label for="address">籍贯:</label>
<select name="address" class="form-control" >
<c:if test="${user.address=='广东'}">
<option value="广东"checked>广东</option>
<option value="广西" >广西</option>
<option value="湖南">湖南</option>
</c:if>
<c:if test="${user.address=='广西'}">
<option value="广东">广东</option>
<option value="广西" checked>广西</option>
<option value="湖南">湖南</option>
</c:if>
<c:if test="${user.address=='湖南'}">
<option value="广东">广东</option>
<option value="广西" >广西</option>
<option value="湖南" checked>湖南</option>
</c:if>
</select>
</div>
<div class="form-group">
<label for="qq">QQ:</label>
<input type="text" class="form-control" name="qq" value="${user.qq}" placeholder="请输入QQ号码"/>
</div>
<div class="form-group">
<label for="email">邮箱:</label>
<input type="text" class="form-control" name="email" value="${user.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>
3.修改功能的servlet
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");
在这里会见面界面上接受到的数据传输到处理数据库表中,同时也会查询所有用户的信息。也就是FindUserByPageServlet,这个servlet将会被多次使用。 FindUserByPageServlet
package cn.itcast.web.servlet;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@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);
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);
}
}
五、删除选中
1.逻辑图
2.JSP代码
<a class="btn btn-primary" href="javascript:void (0);" id="delSelected">删除选中</a>
这一块是界面显示。
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==true){
document.getElementById("form").submit();
}else {
confirm("请先选中您需要删除的条目!");
}
}
该功能的一些逻辑处理。
3.servlet
String[] ids = request.getParameterValues("uid");
UserService service=new UserServiceImpl();
service.delSelectedUser(ids);
response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
和删除功能有些类似,但是它会根据用户选中的用户信息条目来返回用户的id信息。
六、分页查询
1.分析和逻辑图
2.分页查询实体类
package cn.itcast.domain;
import java.util.List;
public class PageBean<T>{
private int totalCount;
private int totalPage;
private List<T> list;
private int currentPage;
private int rows;
public PageBean() {
}
public PageBean(int totalCount, int totalPage, List<T> list, int currentPage, int rows) {
this.totalCount = totalCount;
this.totalPage = totalPage;
this.list = list;
this.currentPage = currentPage;
this.rows = rows;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageBean{" +
"totalCount=" + totalCount +
", totalPage=" + totalPage +
", list=" + list +
", currentPage=" + currentPage +
", rows=" + rows +
'}';
}
}
3.分页查询JSP
<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">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage != i}">
<li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5}">${i}</a></li>
</c:if>
</c:forEach>
这里通过for{即:c:forEach}循环来保证每页显示的数量,和实现它们分页。可以结合实体来看这些数据信息。
4.servlet
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";
}
UserService service=new UserServiceImpl();
PageBean<User> pb=service.findUserByPage(currentPage,rows);
request.setAttribute("pb",pb);
request.getRequestDispatcher("/list.jsp").forward(request,response);
七、复杂条件分页查询功能
1.分析图
2.JSP
</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 id="next_id" href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage+1}&rows=5&name=${condition.name[0]}&name=${condition.address[0]}&name=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
对比分页查询多了一些代码
&name=${condition.name[0]}&name=${condition.address[0]}&name=${condition.email[0]
这里的内容就是用户查询的条件,将它进行了保存。
3.servlet
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);
request.setAttribute("pb",pb);
request.setAttribute("condition",condition);
request.getRequestDispatcher("/list.jsp").forward(request,response);
对比分页查询的servlet多了
Map<String, String[]> condition = request.getParameterMap();
pb=service.findUserByPage(currentPage,rows,condition);
request.setAttribute("condition",condition);
4.sql代码
String sql="select * from user where 1 = 1 ";
StringBuilder sb=new StringBuilder(sql);
Set<String> keySet = condition.keySet();
List<Object> params = new ArrayList<>();
for (String key:keySet){
if ("currentPage".equals(key)|| "rows".equals(key) ){
continue;
}
String value = condition.get(key)[0];
if (value !=null && !"".equals(value)){
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());
总结
欢迎大家使用这些内容。
|