Web案例实战
一、案例需求
1.需求:
实现用户登录与退出登录功能,要求一个用户只能在一处登录(利用Session)
完成对用户表的CRUD操作
使用技术:
JSP、Servlet、Filter、Listener、JDBC、MySQL
2.创建数据库表
CREATE TABLE `users` ( `userid` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(30) DEFAULT NULL, `userpwd` varchar(30) DEFAULT NULL, `usersex` varchar(2) DEFAULT NULL, `phonenumber` varchar(30) DEFAULT NULL, `qqnumber` varchar(20) DEFAULT NULL, PRIMARY KEY (`userid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
|
3 搭建环境
3.1 创建项目
3.2 添加jar包(或maven项目添加依赖)
3.3 添加jstl标签库的约束文件
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
|
3.4 创建包
3.5 创建POJO
package com.bjsxt.pojo;
public class Users { private int userid; private String username; private String userpwd; private String usersex; private String phonenumber; private String qqnumber;
public int getUserid() { return userid; }
public void setUserid(int userid) { this.userid = userid; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getUserpwd() { return userpwd; }
public void setUserpwd(String userpwd) { this.userpwd = userpwd; }
public String getUsersex() { return usersex; }
public void setUsersex(String usersex) { this.usersex = usersex; }
public String getPhonenumber() { return phonenumber; }
public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; }
public String getQqnumber() { return qqnumber; }
public void setQqnumber(String qqnumber) { this.qqnumber = qqnumber; } }
|
3.6 创建JDBC工具类(也可以使用MyBatis )
利用Properties类进行读取值
db.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/bjsxt?useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root
|
JdbcUtils
package com.bjsxt.commons;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ResourceBundle;
public class JdbcUtils { private static String driver; private static String url; private static String username; private static String password; static{ try { ResourceBundle bundle = ResourceBundle.getBundle("db"); driver = bundle.getString("jdbc.driver"); url = bundle.getString("jdbc.url"); username = bundle.getString("jdbc.username"); password = bundle.getString("jdbc.password"); Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
public static Connection getConnection(){ Connection conn = null; try{ conn = DriverManager.getConnection(url,username,password); }catch(Exception e){ e.printStackTrace(); } return conn; }
public static void closeConnection(Connection conn){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
public static void rollbackConnection(Connection conn){ try { conn.rollback(); } catch (SQLException e) { e.printStackTrace(); } } }
|
二、业务实现
1. 用户登录
1.1 创建登录页面
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 10:53 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>欢迎登录后台管理系统</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" src="js/jquery.js"></script> <script src="js/cloud.js" type="text/javascript"></script>
<script language="javascript"> if(window.parent.length > 0){ window.parent.location="login.jsp"; } $(function(){ $('.loginbox').css({'position':'absolute','left':($(window).width()-692)/2}); $(window).resize(function(){ $('.loginbox').css({'position':'absolute','left':($(window).width()-692)/2}); }) }); function change(){ $("#code").attr("src","validateCode.do?"+Math.random()); } </script>
</head>
<body style="background-color:#1c77ac; background-image:url(images/light.png); background-repeat:no-repeat; background-position:center top; overflow:hidden;">
<div id="mainBody"> <div id="cloud1" class="cloud"></div> <div id="cloud2" class="cloud"></div> </div>
<div class="logintop"> <ul> <li><a href="#">回首页</a></li> <li><a href="#">帮助</a></li> <li><a href="#">关于</a></li> </ul> </div>
<div class="loginbody">
${msg} <div class="loginbox loginbox2">
<form action="login.do" method="post"> <ul> <li><input name="username" type="text" class="loginuser" value="admin" onclick="JavaScript:this.value=''"/></li> <li><input name="userpwd" type="password" class="loginpwd" value="密码" onclick="JavaScript:this.value=''"/></li> <li class="yzm"> <span><input name="code" type="text" value="验证码" onclick="JavaScript:this.value=''"/></span><cite><img id="code" src="validateCode.do" onclick="change()"></cite> </li> <li><input name="" type="submit" class="loginbtn" value="登录" onclick="javascript:window.location='main.html'" /></li> </ul> </form> </div> </div> </body> </html>
|
1.2 创建登陆业务持久层
package com.bjsxt.dao;
import com.bjsxt.pojo.Users;
public interface UserLoginDao { public Users selectUsersByUserNameAndUserPwd(String username,String userpwd); }
|
package com.bjsxt.dao.impl;
import com.bjsxt.commons.JdbcUtils; import com.bjsxt.dao.UserLoginDao; import com.bjsxt.pojo.Users;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet;
public class UserLoginDaoImpl implements UserLoginDao {
@Override public Users selectUsersByUserNameAndUserPwd(String username, String userpwd) { Users user = null; Connection conn = null; try{ conn = JdbcUtils.getConnection(); PreparedStatement ps = conn.prepareStatement("select * from users where username = ? and userpwd = ?"); ps.setString(1,username); ps.setString(2,userpwd); ResultSet resultSet = ps.executeQuery(); while(resultSet.next()){ user = new Users(); user.setUsersex(resultSet.getString("usersex")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); } }catch(Exception e){ e.printStackTrace(); }finally{
} return user; } }
|
1.4 创建登录业务的业务层
用户登录状态的自定义异常
package com.bjsxt.exception;
public class UserNotFoundException extends RuntimeException{ public UserNotFoundException() { }
public UserNotFoundException(String message) { super(message); }
public UserNotFoundException(String message, Throwable cause) { super(message, cause); } }
|
创建业务层
package com.bjsxt.service;
import com.bjsxt.pojo.Users;
public interface UserLoginService { Users userLogin(String username,String userpwd); }
|
package com.bjsxt.service.impl;
import com.bjsxt.dao.UserLoginDao; import com.bjsxt.dao.impl.UserLoginDaoImpl; import com.bjsxt.exception.UserNotFoundException; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserLoginService;
public class UserLoginServiceImpl implements UserLoginService {
@Override public Users userLogin(String username, String userpwd) { UserLoginDao userLoginDao = new UserLoginDaoImpl(); Users users = userLoginDao.selectUsersByUserNameAndUserPwd(username, userpwd); if(users == null){ throw new UserNotFoundException("用户名或密码有误!"); } return users; } }
|
1.4 创建登录业务的web层
1.4.1 创建Servlert
package com.bjsxt.web.servlet;
import com.bjsxt.commons.Constants; import com.bjsxt.exception.UserNotFoundException; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserLoginService; import com.bjsxt.service.impl.UserLoginServiceImpl;
import javax.servlet.ServletContext; 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;
@WebServlet("/login.do") public class UserLoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); try{ UserLoginService userLoginService = new UserLoginServiceImpl(); Users users = userLoginService.userLogin(username, userpwd); HttpSession session = req.getSession(); session.setAttribute(Constants.USER_SESSION_KEY,users); resp.sendRedirect("main.jsp"); } }catch(UserNotFoundException e){ req.setAttribute("msg",e.getMessage()); req.getRequestDispatcher("login.jsp").forward(req,resp); }catch (Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
1.4.2 添加登录后的首页
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 11:36 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>信息管理系统界面</title> </head> <frameset rows="*,31" cols="*" frameborder="no" border="0" framespacing="0"> <frameset cols="187,*" frameborder="no" border="0" framespacing="0"> <frame src="left.jsp" name="leftFrame" scrolling="No" noresize="noresize" id="leftFrame" title="leftFrame" /> <frame src="index.jsp" name="rightFrame" id="rightFrame" title="rightFrame" /> </frameset> <frame src="footer.jsp" name="bottomFrame" scrolling="No" noresize="noresize" id="bottomFrame" title="bottomFrame" /> </frameset> <noframes><body> </body></noframes> </html> </html>
|
1.4.3 创建登录业务的Filter
package com.bjsxt.web.filter;
import com.bjsxt.commons.Constants; import com.bjsxt.pojo.Users;
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException;
@WebFilter(urlPatterns = {"*.do","*.jsp"}) public class UserLoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {
} @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; String uri = request.getRequestURI(); if(uri.indexOf("login.jsp") != -1 || uri.indexOf("login.do") != -1|| uri.indexOf("validateCode.do") != -1){ filterChain.doFilter(servletRequest, servletResponse); }else{ HttpSession session = request.getSession(); Users users = (Users) session.getAttribute(Constants.USER_SESSION_KEY); if(users != null){ filterChain.doFilter(servletRequest, servletResponse); }else{ request.setAttribute(Constants.REQUEST_MSG,"不登录不好使!"); request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse); } } }
@Override public void destroy() {
} }
|
1.5 用户只能在一处登录
1.5.1 修改处理登录请求的Servlet
package com.bjsxt.web.servlet;
import com.bjsxt.commons.Constants; import com.bjsxt.exception.UserNotFoundException; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserLoginService; import com.bjsxt.service.impl.UserLoginServiceImpl;
import javax.servlet.ServletContext; 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;
@WebServlet("/login.do") public class UserLoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); try{ UserLoginService userLoginService = new UserLoginServiceImpl(); Users users = userLoginService.userLogin(username, userpwd); HttpSession session = req.getSession(); session.setAttribute(Constants.USER_SESSION_KEY,users); ServletContext servletContext = this.getServletContext(); HttpSession temp = (HttpSession) servletContext.getAttribute(users.getUserid()+""); if(temp != null){ servletContext.removeAttribute(users.getUserid()+""); temp.invalidate(); } servletContext.setAttribute(users.getUserid()+"",session); resp.sendRedirect("main.jsp"); }catch(UserNotFoundException e){ req.setAttribute("msg",e.getMessage()); req.getRequestDispatcher("login.jsp").forward(req,resp); }catch (Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
1.5.2 修改登录页面
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 10:53 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>欢迎登录后台管理系统</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" src="js/jquery.js"></script> <script src="js/cloud.js" type="text/javascript"></script>
<script language="javascript"> if(window.parent.length > 0){ window.parent.location="login.jsp"; } $(function(){ $('.loginbox').css({'position':'absolute','left':($(window).width()-692)/2}); $(window).resize(function(){ $('.loginbox').css({'position':'absolute','left':($(window).width()-692)/2}); }) }); function change(){ $("#code").attr("src","validateCode.do?"+Math.random()); } </script>
</head>
<body style="background-color:#1c77ac; background-image:url(images/light.png); background-repeat:no-repeat; background-position:center top; overflow:hidden;">
<div id="mainBody"> <div id="cloud1" class="cloud"></div> <div id="cloud2" class="cloud"></div> </div>
<div class="logintop"> <ul> <li><a href="#">回首页</a></li> <li><a href="#">帮助</a></li> <li><a href="#">关于</a></li> </ul> </div>
<div class="loginbody">
${msg} <div class="loginbox loginbox2">
<form action="login.do" method="post"> <ul> <li><input name="username" type="text" class="loginuser" value="admin" onclick="JavaScript:this.value=''"/></li> <li><input name="userpwd" type="passwor" class="loginpwd" value="密码" onclick="JavaScript:this.value=''"/></li> <li class="yzm"> <span><input name="code" type="text" value="验证码" onclick="JavaScript:this.value=''"/></span><cite><img id="code" src="validateCode.do" onclick="change()"></cite> </li> <li><input name="" type="submit" class="loginbtn" value="登录" onclick="javascript:window.location='main.html'" /></li> </ul> </form> </div> </div> </body> </html>
|
1.5.3 解决HttpSession超时销毁时的异常问题
添加产生验证的servlet
package com.bjsxt.web.listener;
import com.bjsxt.commons.Constants; import com.bjsxt.pojo.Users;
import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener;
@WebListener public class HttpSessionLifecycleListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent se) {
}
@Override public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); ServletContext servletContext = session.getServletContext(); Users users = (Users) session.getAttribute(Constants.USER_SESSION_KEY); servletContext.removeAttribute(users.getUserid()+""); } }
|
1.4 在登陆中添加验证码功能
添加产生验证的Servlet
package com.bjsxt.commons;
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random;
import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
@WebServlet("/validateCode.do") public class ValidateCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 70, height = 45; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); Random random = new Random(); g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); g.setFont(new Font("Times New Roman", Font.PLAIN, 20)); g.setColor(getRandColor(160, 200)); for (int i = 0; i < 155; i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x, y, x + xl, y + yl); } String sRand = ""; for (int i = 0; i < 4; i++) { String rand = String.valueOf(random.nextInt(10)); sRand += rand; g.setColor(new Color(20 + random.nextInt(110), 20 + random .nextInt(110), 20 + random.nextInt(110))); g.drawString(rand, 13 * i + 6, 16); } g.dispose(); try { ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { System.out.println("验证码图片产生出现错误:" + e.toString()); } request.getSession().setAttribute(Constants.VALIDATE_CODE_KEY, sRand); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response); }
private Color getRandColor(int fc, int bc) { Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } }
|
修改登录页面
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 10:53 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>欢迎登录后台管理系统</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" src="js/jquery.js"></script> <script src="js/cloud.js" type="text/javascript"></script>
<script language="javascript"> if(window.parent.length > 0){ window.parent.location="login.jsp"; } $(function(){ $('.loginbox').css({'position':'absolute','left':($(window).width()-692)/2}); $(window).resize(function(){ $('.loginbox').css({'position':'absolute','left':($(window).width()-692)/2}); }) }); function change(){ $("#code").attr("src","validateCode.do?"+Math.random()); } </script>
</head>
<body style="background-color:#1c77ac; background-image:url(images/light.png); background-repeat:no-repeat; background-position:center top; overflow:hidden;">
<div id="mainBody"> <div id="cloud1" class="cloud"></div> <div id="cloud2" class="cloud"></div> </div>
<div class="logintop"> <ul> <li><a href="#">回首页</a></li> <li><a href="#">帮助</a></li> <li><a href="#">关于</a></li> </ul> </div>
<div class="loginbody">
${msg} <div class="loginbox loginbox2">
<form action="login.do" method="post"> <ul> <li><input name="username" type="text" class="loginuser" value="admin" onclick="JavaScript:this.value=''"/></li> <li><input name="userpwd" type="passwor" class="loginpwd" value="密码" onclick="JavaScript:this.value=''"/></li> <li class="yzm"> <span><input name="code" type="text" value="验证码" onclick="JavaScript:this.value=''"/></span><cite><img id="code" src="validateCode.do" onclick="change()"></cite> </li> <li><input name="" type="submit" class="loginbtn" value="登录" onclick="javascript:window.location='main.html'" /></li> </ul> </form> </div> </div> </body> </html>
|
修改用户登录过滤器
package com.bjsxt.web.filter;
import com.bjsxt.commons.Constants; import com.bjsxt.pojo.Users;
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException;
@WebFilter(urlPatterns = {"*.do","*.jsp"}) public class UserLoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {
}
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; String uri = request.getRequestURI(); if(uri.indexOf("login.jsp") != -1 || uri.indexOf("login.do") != -1|| uri.indexOf("validateCode.do") != -1){ filterChain.doFilter(servletRequest, servletResponse); }else{ HttpSession session = request.getSession(); Users users = (Users) session.getAttribute(Constants.USER_SESSION_KEY); if(users != null){ filterChain.doFilter(servletRequest, servletResponse); }else{ request.setAttribute(Constants.REQUEST_MSG,"不登录不好使!"); request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse); } } }
@Override public void destroy() {
} }
|
修改处理登录请求的Servlet
package com.bjsxt.web.servlet;
import com.bjsxt.commons.Constants; import com.bjsxt.exception.UserNotFoundException; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserLoginService; import com.bjsxt.service.impl.UserLoginServiceImpl;
import javax.servlet.ServletContext; 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;
@WebServlet("/login.do") public class UserLoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); String code = req.getParameter("code"); try{ HttpSession session = req.getSession(); String codeTemp = (String)session.getAttribute(Constants.VALIDATE_CODE_KEY); if(codeTemp.equals(code)){ UserLoginService userLoginService = new UserLoginServiceImpl(); Users users = userLoginService.userLogin(username, userpwd);
session.setAttribute(Constants.USER_SESSION_KEY,users); ServletContext servletContext = this.getServletContext(); HttpSession temp = (HttpSession) servletContext.getAttribute(users.getUserid()+""); if(temp != null){ servletContext.removeAttribute(users.getUserid()+""); temp.invalidate(); } servletContext.setAttribute(users.getUserid()+"",session); resp.sendRedirect("main.jsp"); }else{ req.setAttribute(Constants.REQUEST_MSG,"验证码有误,请重新输入"); req.getRequestDispatcher("login.jsp").forward(req,resp); } }catch(UserNotFoundException e){ req.setAttribute("msg",e.getMessage()); req.getRequestDispatcher("login.jsp").forward(req,resp); }catch (Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
2 用户退出登录
修改left.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script language="JavaScript" src="js/jquery.js"></script>
<script type="text/javascript"> $(function(){ $(".menuson .header").click(function(){ var $parent = $(this).parent(); $(".menuson>li.active").not($parent).removeClass("active open").find('.sub-menus').hide();
$parent.addClass("active"); if(!!$(this).next('.sub-menus').size()){ if($parent.hasClass("open")){ $parent.removeClass("open").find('.sub-menus').hide(); }else{ $parent.addClass("open").find('.sub-menus').show(); }
} });
$('.sub-menus li').click(function(e) { $(".sub-menus li.active").removeClass("active") $(this).addClass("active"); });
$('.title').click(function(){ var $ul = $(this).next('ul'); $('dd').find('.menuson').slideUp(); if($ul.is(':visible')){ $(this).next('.menuson').slideUp(); }else{ $(this).next('.menuson').slideDown(); } }); }) </script>
</head>
<body style="background:#f0f9fd;"> <div class="lefttop"><span></span>导航菜单</div>
<dl class="leftmenu"> <dd> <div class="title"><span><img src="images/leftico03.png" /></span>用户管理</div> <ul class="menuson"> <li><cite></cite><a href="usermanager/addUser.jsp" target="rightFrame">添加用户</a><i></i></li> <li><cite></cite><a href="usermanager/findUser.jsp" target="rightFrame">查询用户</a><i></i></li> <li><cite></cite><a href="logout.do" target="rightFrame">退出登录</a><i></i></li> </ul> </dd> </dl>
</body> </html>
|
创建Servlet
package com.bjsxt.web.servlet;
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;
@WebServlet("/logout.do") public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.invalidate(); resp.sendRedirect("login.jsp"); } }
|
3 添加用户业务
3.1 创建添加用户持久层
package com.bjsxt.dao;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerDao { void insertUser(Users users); }
|
package com.bjsxt.dao.impl;
import com.bjsxt.commons.JdbcUtils; import com.bjsxt.dao.UserManagerDao; import com.bjsxt.pojo.Users;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;
public class UserManagerDaoImpl implements UserManagerDao {
@Override public void insertUser(Users users) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into users values(default,?,?,?,?,?)"); ps.setString(1,users.getUsername()); ps.setString(2,users.getUserpwd()); ps.setString(3,users.getUsersex()); ps.setString(4,users.getPhonenumber()); ps.setString(5,users.getQqnumber()); ps.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally{ JdbcUtils.closeConnection(conn); } }
|
3.2 创建添加用户业务层
package com.bjsxt.service;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerService { void addUser(Users users); }
|
package com.bjsxt.service.impl;
import com.bjsxt.dao.UserManagerDao; import com.bjsxt.dao.impl.UserManagerDaoImpl; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService;
import java.util.List;
public class UserManagerServiceImpl implements UserManagerService {
@Override public void addUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.insertUser(users); }
}
|
3.3 创建添加用户的Servlet
package com.bjsxt.web.servlet;
import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService; import com.bjsxt.service.impl.UserManagerServiceImpl;
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.List;
@WebServlet("/userManager.do") public class UserManagerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("addUser".equals(flag)){ this.addUser(req,resp); }else if("findUser".equals(flag)){ this.findUser(req,resp); }else if("preUpdate".equals(flag)){ this.preUpdate(req,resp); }else if("modifyUser".equals(flag)){ this.modifyUser(req,resp); }else{ this.dropUser(req,resp); } } private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Users users = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.addUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } private Users createUsers(HttpServletRequest req){ String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); String usersex = req.getParameter("usersex"); String phonenumber = req.getParameter("phonenumber"); String qqnumber = req.getParameter("qqnumber"); Users users = new Users(); users.setQqnumber(qqnumber); users.setPhonenumber(phonenumber); users.setUsername(username); users.setUserpwd(userpwd); users.setUsersex(usersex); return users; }
private void findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ Users user = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); List<Users> list = userManagerService.findUser(user); req.setAttribute("list",list); req.getRequestDispatcher("usermanager/viewUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void preUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); Users user = userManagerService.findUserByUserId(Integer.parseInt(userid)); req.setAttribute("user",user); req.getRequestDispatcher("usermanager/updateUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); Users users = this.createUsers(req); users.setUserid(Integer.parseInt(userid)); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.modifyUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void dropUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.dropUser(Integer.parseInt(userid)); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
3.4 创建添加用户页面
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 16:50 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="../css/style.css" rel="stylesheet" type="text/css" /> <link href="../css/style.css" rel="stylesheet" type="text/css" /> <link href="../css/select.css" rel="stylesheet" type="text/css" /> </head>
<body>
<div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">用户管理</a></li> <li><a href="#">添加用户</a></li> </ul> </div>
<div class="formbody">
<div class="formtitle"><span>基本信息</span></div> <%-- http: <%-- http: <form action="../userManager.do" method="post"> <input type="hidden" name="flag" value="addUser"/> <ul class="forminfo"> <li> <label>用户名</label> <input name="username" type="text" class="dfinput" /></li> <li> <li> <label>用户密码</label> <input name="userpwd" type="text" class="dfinput" /><i></i></li> <li> <label>性别</label><cite> <input name="usersex" type="radio" value="1" checked="checked" />男 <input name="usersex" type="radio" value="0" />女
</li> <li> <label>联系方式</label> <input name="phonenumber" type="text" class="dfinput" /> </li> <li> <label>QQ号</label> <input name="qqnumber" type="text" class="dfinput" /> </li> <li> <label> </label> <input type="submit" class="btn" value="确认保存" /> </li> </ul> </form> </div>
</body>
</html>
|
创建成功页面
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 16:54 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> function submitForm(){ window.close();
}
</script> </head>
<body> <div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">操作提示</a></li> </ul> </div>
操作成功!
</body> </html>
|
4 查询用户业务
4.1 创建查询用户持久层
package com.bjsxt.dao;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerDao { void insertUser(Users users); List<Users> selectUsersByProperty(Users users);
}
|
package com.bjsxt.dao.impl;
import com.bjsxt.commons.JdbcUtils; import com.bjsxt.dao.UserManagerDao; import com.bjsxt.pojo.Users;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;
public class UserManagerDaoImpl implements UserManagerDao {
@Override public void insertUser(Users users) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into users values(default,?,?,?,?,?)"); ps.setString(1,users.getUsername()); ps.setString(2,users.getUserpwd()); ps.setString(3,users.getUsersex()); ps.setString(4,users.getPhonenumber()); ps.setString(5,users.getQqnumber()); ps.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally{ JdbcUtils.closeConnection(conn); } }
@Override public List<Users> selectUsersByProperty(Users users) { Connection conn = null; List<Users> list = new ArrayList<>(); try{ conn = JdbcUtils.getConnection(); String sql = this.createSQL(users); PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ Users user = new Users(); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUsersex(resultSet.getString("usersex")); list.add(user); } }catch(Exception e){ e.printStackTrace(); }finally{ JdbcUtils.closeConnection(conn); } return list; }
private String createSQL(Users users){ StringBuffer stringBuffer = new StringBuffer("select * from users where 1=1 "); if(users.getUsersex() != null && users.getUsersex().length() > 0){ stringBuffer.append(" and usersex = "+users.getUsersex()); } if(users.getQqnumber() != null && users.getQqnumber().length() > 0){ stringBuffer.append(" and qqnumber = "+users.getQqnumber()); } if(users.getUsername() != null && users.getUsername().length() > 0){ stringBuffer.append(" and username = "+users.getUsername()); } if(users.getPhonenumber() != null &&users.getPhonenumber().length() > 0){ stringBuffer.append(" and phonenumber = "+users.getPhonenumber()); } return stringBuffer.toString(); } }
|
4.2 创建查询用户业务层
package com.bjsxt.service;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerService { void addUser(Users users); List<Users> findUser(Users users); }
|
package com.bjsxt.service.impl;
import com.bjsxt.dao.UserManagerDao; import com.bjsxt.dao.impl.UserManagerDaoImpl; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService;
import java.util.List;
public class UserManagerServiceImpl implements UserManagerService {
@Override public void addUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.insertUser(users); }
@Override public List<Users> findUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); return userManagerDao.selectUsersByProperty(users); }
}
|
4.3 创建查询用户的Servlet
package com.bjsxt.web.servlet;
import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService; import com.bjsxt.service.impl.UserManagerServiceImpl;
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.List;
@WebServlet("/userManager.do") public class UserManagerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("addUser".equals(flag)){ this.addUser(req,resp); }else if("findUser".equals(flag)){ this.findUser(req,resp); }else if("preUpdate".equals(flag)){ this.preUpdate(req,resp); }else if("modifyUser".equals(flag)){ this.modifyUser(req,resp); }else{ this.dropUser(req,resp); } } private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Users users = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.addUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } private Users createUsers(HttpServletRequest req){ String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); String usersex = req.getParameter("usersex"); String phonenumber = req.getParameter("phonenumber"); String qqnumber = req.getParameter("qqnumber"); Users users = new Users(); users.setQqnumber(qqnumber); users.setPhonenumber(phonenumber); users.setUsername(username); users.setUserpwd(userpwd); users.setUsersex(usersex); return users; }
private void findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ Users user = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); List<Users> list = userManagerService.findUser(user); req.setAttribute("list",list); req.getRequestDispatcher("usermanager/viewUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void preUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); Users user = userManagerService.findUserByUserId(Integer.parseInt(userid)); req.setAttribute("user",user); req.getRequestDispatcher("usermanager/updateUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); Users users = this.createUsers(req); users.setUserid(Integer.parseInt(userid)); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.modifyUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void dropUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.dropUser(Integer.parseInt(userid)); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
4.4 创建查询用户与显示结果的页面
创建findUser.jsp页面
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 19:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="../css/style.css" rel="stylesheet" type="text/css" /> <link href="../css/select.css" rel="stylesheet" type="text/css" /> </head>
<body>
<div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">用户管理</a></li> <li><a href="#">查询用户</a></li> </ul> </div>
<div class="rightinfo"> <form action="../userManager.do" method="post"> <input type="hidden" name="flag" value="findUser"/> <ul class="prosearch"> <li> <label>查询:</label> <i>用户名</i> <a> <input name="username" type="text" class="scinput" /> </a> </li> <li> <label>性别:</label> <input name="usersex" type="radio" value="1" checked="checked" /> 男 <input name="usersex" type="radio" value="0" /> 女 </li> <li> <label>手机号:</label> <a> <input name="phonenumber" type="text" class="scinput" /> </a> </li> <li> <label>QQ号:</label> <a> <input name="qqnumber" type="text" class="scinput" /> </a> </li> <a> <input type="submit" class="sure" value="查询"/> </a> </ul> </form> </body> </html>
|
创建viewUser.jsp页面
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 19:04 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" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head>
<body>
<div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">用户管理</a></li> <li><a href="#">查询用户</a></li> <li><a href="#">查询结果</a></li> </ul> </div>
<div class="rightinfo">
<div class="formtitle1"><span>用户列表</span></div>
<table class="tablelist" > <thead> <tr> <th>序号</th> <th>用户名</th> <th>用户性别</th> <th>手机号</th> <th>QQ号</th> <th>操作</th> </tr> </thead>
<tbody> <c:forEach items="${list}" var="user" varStatus="status"> <tr> <td>${status.count}</td> <td>${user.username}</td> <td> <c:choose> <c:when test="${user.usersex == 1}"> 男 </c:when> <c:otherwise> 女 </c:otherwise> </c:choose> </td> <td>${user.phonenumber}</td> <td>${user.qqnumber}</td> <td><a href="userManager.do?flag=preUpdate&userid=${user.userid}" class="tablelink">修改</a> <a href="userManager.do?userid=${user.userid}" class="tablelink click"> 删除</a></td> </tr> </c:forEach> </tbody> </table>
<div class="tip"> <div class="tiptop"><span>提示信息</span><a></a></div>
<div class="tipinfo"> <span><img src="images/ticon.png" /></span> <div class="tipright"> <p>是否确认对信息的修改 ?</p> <cite>如果是请点击确定按钮 ,否则请点取消。</cite> </div> </div>
<div class="tipbtn"> <input name="" type="button" class="sure" value="确定" /> <input name="" type="button" class="cancel" value="取消" /> </div>
</div>
</div> </body> </html>
|
5 更新用户业务
5.1 预更新用户的查询
5.1.1 创建预更新用户查询持久层
package com.bjsxt.dao;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerDao { void insertUser(Users users); List<Users> selectUsersByProperty(Users users); Users selectUserByUserId(int userid); }
|
package com.bjsxt.dao.impl;
import com.bjsxt.commons.JdbcUtils; import com.bjsxt.dao.UserManagerDao; import com.bjsxt.pojo.Users;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;
public class UserManagerDaoImpl implements UserManagerDao {
@Override public void insertUser(Users users) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into users values(default,?,?,?,?,?)"); ps.setString(1,users.getUsername()); ps.setString(2,users.getUserpwd()); ps.setString(3,users.getUsersex()); ps.setString(4,users.getPhonenumber()); ps.setString(5,users.getQqnumber()); ps.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally{ JdbcUtils.closeConnection(conn); } }
@Override public List<Users> selectUsersByProperty(Users users) { Connection conn = null; List<Users> list = new ArrayList<>(); try{ conn = JdbcUtils.getConnection(); String sql = this.createSQL(users); PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ Users user = new Users(); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUsersex(resultSet.getString("usersex")); list.add(user); } }catch(Exception e){ e.printStackTrace(); }finally{ JdbcUtils.closeConnection(conn); } return list; }
@Override public Users selectUserByUserId(int userid) { Connection conn = null; Users user = null; try{ conn = JdbcUtils.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement("select * from users where userid = ?"); preparedStatement.setInt(1,userid); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ user = new Users(); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUsersex(resultSet.getString("usersex")); } }catch(Exception e){ e.printStackTrace(); }finally{ JdbcUtils.closeConnection(conn); } return user; }
private String createSQL(Users users){ StringBuffer stringBuffer = new StringBuffer("select * from users where 1=1 "); if(users.getUsersex() != null && users.getUsersex().length() > 0){ stringBuffer.append(" and usersex = "+users.getUsersex()); } if(users.getQqnumber() != null && users.getQqnumber().length() > 0){ stringBuffer.append(" and qqnumber = "+users.getQqnumber()); } if(users.getUsername() != null && users.getUsername().length() > 0){ stringBuffer.append(" and username = "+users.getUsername()); } if(users.getPhonenumber() != null &&users.getPhonenumber().length() > 0){ stringBuffer.append(" and phonenumber = "+users.getPhonenumber()); } return stringBuffer.toString(); } }
|
5.1.2 创建预更新用户业务层
package com.bjsxt.service;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerService { void addUser(Users users); List<Users> findUser(Users users); Users findUserByUserId(int userid); }
|
package com.bjsxt.service.impl;
import com.bjsxt.dao.UserManagerDao; import com.bjsxt.dao.impl.UserManagerDaoImpl; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService;
import java.util.List;
public class UserManagerServiceImpl implements UserManagerService {
@Override public void addUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.insertUser(users); }
@Override public List<Users> findUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); return userManagerDao.selectUsersByProperty(users); }
@Override public Users findUserByUserId(int userid) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); return userManagerDao.selectUserByUserId(userid); }
}
|
5.1.3 创建预更新用户的Servlet
package com.bjsxt.web.servlet;
import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService; import com.bjsxt.service.impl.UserManagerServiceImpl;
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.List;
@WebServlet("/userManager.do") public class UserManagerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("addUser".equals(flag)){ this.addUser(req,resp); }else if("findUser".equals(flag)){ this.findUser(req,resp); }else if("preUpdate".equals(flag)){ this.preUpdate(req,resp); }else if("modifyUser".equals(flag)){ this.modifyUser(req,resp); }else{ this.dropUser(req,resp); } } private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Users users = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.addUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } private Users createUsers(HttpServletRequest req){ String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); String usersex = req.getParameter("usersex"); String phonenumber = req.getParameter("phonenumber"); String qqnumber = req.getParameter("qqnumber"); Users users = new Users(); users.setQqnumber(qqnumber); users.setPhonenumber(phonenumber); users.setUsername(username); users.setUserpwd(userpwd); users.setUsersex(usersex); return users; }
private void findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ Users user = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); List<Users> list = userManagerService.findUser(user); req.setAttribute("list",list); req.getRequestDispatcher("usermanager/viewUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void preUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); Users user = userManagerService.findUserByUserId(Integer.parseInt(userid)); req.setAttribute("user",user); req.getRequestDispatcher("usermanager/updateUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); Users users = this.createUsers(req); users.setUserid(Integer.parseInt(userid)); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.modifyUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void dropUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.dropUser(Integer.parseInt(userid)); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
5.1.4 创建更新用户页面
修改viewUser.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 19:04 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" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head>
<body>
<div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">用户管理</a></li> <li><a href="#">查询用户</a></li> <li><a href="#">查询结果</a></li> </ul> </div>
<div class="rightinfo">
<div class="formtitle1"><span>用户列表</span></div>
<table class="tablelist" > <thead> <tr> <th>序号</th> <th>用户名</th> <th>用户性别</th> <th>手机号</th> <th>QQ号</th> <th>操作</th> </tr> </thead>
<tbody> <c:forEach items="${list}" var="user" varStatus="status"> <tr> <td>${status.count}</td> <td>${user.username}</td> <td> <c:choose> <c:when test="${user.usersex == 1}"> 男 </c:when> <c:otherwise> 女 </c:otherwise> </c:choose> </td> <td>${user.phonenumber}</td> <td>${user.qqnumber}</td> <td><a href="userManager.do?flag=preUpdate&userid=${user.userid}" class="tablelink">修改</a> <a href="userManager.do?userid=${user.userid}" class="tablelink click"> 删除</a></td> </tr> </c:forEach> </tbody> </table>
<div class="tip"> <div class="tiptop"><span>提示信息</span><a></a></div>
<div class="tipinfo"> <span><img src="images/ticon.png" /></span> <div class="tipright"> <p>是否确认对信息的修改 ?</p> <cite>如果是请点击确定按钮 ,否则请点取消。</cite> </div> </div>
<div class="tipbtn"> <input name="" type="button" class="sure" value="确定" /> <input name="" type="button" class="cancel" value="取消" /> </div>
</div>
</div> </body> </html>
|
创建updateUser.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 20:00 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" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head>
<body>
<div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">用户管理</a></li> <li><a href="#">修改用户</a></li> </ul> </div>
<div class="formbody">
<div class="formtitle"><span>基本信息</span></div> <form action="userManager.do" method="post"> <input type="hidden" name="flag" value="modifyUser"/> <%-- 获取userid --%> <input type="hidden" name="userid" value="${user.userid}"/> <ul class="forminfo"> <li><label>用户名</label><input name="username" type="text" class="dfinput" value="${user.username}"/> </li> <li> <label>性别</label><cite> <c:choose> <c:when test="${user.usersex == 1}"> <input name="usersex" type="radio" value="1" checked="checked" />男 <input name="usersex" type="radio" value="0" />女 </c:when> <c:otherwise> <input name="usersex" type="radio" value="1" />男 <input name="usersex" type="radio" value="0" checked="checked" />女 </c:otherwise> </c:choose>
</li> <li><label>手机号</label><input name="phonenumber" type="text" class="dfinput" value="${user.phonenumber}"/></li> <li><label>QQ号</label><input name="qqnumber" type="text" class="dfinput" value="${user.qqnumber}"/></li> <li><label> </label><input type="submit" class="btn" value="确认保存"/></li> </ul> </form> </div> </body> </html>
|
5.2 更新用户操作
5.2.1 创建更新用户持久层
package com.bjsxt.dao;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerDao { void insertUser(Users users); List<Users> selectUsersByProperty(Users users); Users selectUserByUserId(int userid); void updateUserByUserId(Users users); }
|
package com.bjsxt.dao.impl;
import com.bjsxt.commons.JdbcUtils; import com.bjsxt.dao.UserManagerDao; import com.bjsxt.pojo.Users;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;
public class UserManagerDaoImpl implements UserManagerDao {
@Override public void insertUser(Users users) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into users values(default,?,?,?,?,?)"); ps.setString(1,users.getUsername()); ps.setString(2,users.getUserpwd()); ps.setString(3,users.getUsersex()); ps.setString(4,users.getPhonenumber()); ps.setString(5,users.getQqnumber()); ps.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally{ JdbcUtils.closeConnection(conn); } }
@Override public List<Users> selectUsersByProperty(Users users) { Connection conn = null; List<Users> list = new ArrayList<>(); try{ conn = JdbcUtils.getConnection(); String sql = this.createSQL(users); PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ Users user = new Users(); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUsersex(resultSet.getString("usersex")); list.add(user); } }catch(Exception e){ e.printStackTrace(); }finally{ JdbcUtils.closeConnection(conn); } return list; }
@Override public Users selectUserByUserId(int userid) { Connection conn = null; Users user = null; try{ conn = JdbcUtils.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement("select * from users where userid = ?"); preparedStatement.setInt(1,userid); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ user = new Users(); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUsersex(resultSet.getString("usersex")); } }catch(Exception e){ e.printStackTrace(); }finally{ JdbcUtils.closeConnection(conn); } return user; }
@Override public void updateUserByUserId(Users users) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement preparedStatement = conn.prepareStatement("update users set username=? ,usersex = ?,phonenumber=?,qqnumber = ? where userid = ? "); preparedStatement.setString(1,users.getUsername()); preparedStatement.setString(2,users.getUsersex()); preparedStatement.setString(3,users.getPhonenumber()); preparedStatement.setString(4,users.getQqnumber()); preparedStatement.setInt(5,users.getUserid()); preparedStatement.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally { JdbcUtils.closeConnection(conn); } }
private String createSQL(Users users){ StringBuffer stringBuffer = new StringBuffer("select * from users where 1=1 "); if(users.getUsersex() != null && users.getUsersex().length() > 0){ stringBuffer.append(" and usersex = "+users.getUsersex()); } if(users.getQqnumber() != null && users.getQqnumber().length() > 0){ stringBuffer.append(" and qqnumber = "+users.getQqnumber()); } if(users.getUsername() != null && users.getUsername().length() > 0){ stringBuffer.append(" and username = "+users.getUsername()); } if(users.getPhonenumber() != null &&users.getPhonenumber().length() > 0){ stringBuffer.append(" and phonenumber = "+users.getPhonenumber()); } return stringBuffer.toString(); } }
|
5.2.2 创建更新用户业务层
package com.bjsxt.service;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerService { void addUser(Users users); List<Users> findUser(Users users); Users findUserByUserId(int userid); void modifyUser(Users users);
}
|
package com.bjsxt.service.impl;
import com.bjsxt.dao.UserManagerDao; import com.bjsxt.dao.impl.UserManagerDaoImpl; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService;
import java.util.List;
public class UserManagerServiceImpl implements UserManagerService {
@Override public void addUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.insertUser(users); }
@Override public List<Users> findUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); return userManagerDao.selectUsersByProperty(users); }
@Override public Users findUserByUserId(int userid) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); return userManagerDao.selectUserByUserId(userid); }
@Override public void modifyUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.updateUserByUserId(users); }
}
|
5.2.3 创建更新用户Servlet
package com.bjsxt.web.servlet;
import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService; import com.bjsxt.service.impl.UserManagerServiceImpl;
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.List;
@WebServlet("/userManager.do") public class UserManagerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("addUser".equals(flag)){ this.addUser(req,resp); }else if("findUser".equals(flag)){ this.findUser(req,resp); }else if("preUpdate".equals(flag)){ this.preUpdate(req,resp); }else if("modifyUser".equals(flag)){ this.modifyUser(req,resp); }else{ this.dropUser(req,resp); } } private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Users users = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.addUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } private Users createUsers(HttpServletRequest req){ String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); String usersex = req.getParameter("usersex"); String phonenumber = req.getParameter("phonenumber"); String qqnumber = req.getParameter("qqnumber"); Users users = new Users(); users.setQqnumber(qqnumber); users.setPhonenumber(phonenumber); users.setUsername(username); users.setUserpwd(userpwd); users.setUsersex(usersex); return users; }
private void findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ Users user = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); List<Users> list = userManagerService.findUser(user); req.setAttribute("list",list); req.getRequestDispatcher("usermanager/viewUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void preUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); Users user = userManagerService.findUserByUserId(Integer.parseInt(userid)); req.setAttribute("user",user); req.getRequestDispatcher("usermanager/updateUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); Users users = this.createUsers(req); users.setUserid(Integer.parseInt(userid)); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.modifyUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
5.2.4 修改更新用户页面
修改updateUser.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 20:00 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" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head>
<body>
<div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">用户管理</a></li> <li><a href="#">修改用户</a></li> </ul> </div>
<div class="formbody">
<div class="formtitle"><span>基本信息</span></div> <form action="userManager.do" method="post"> <input type="hidden" name="flag" value="modifyUser"/> <%-- 获取userid --%> <input type="hidden" name="userid" value="${user.userid}"/> <ul class="forminfo"> <li><label>用户名</label><input name="username" type="text" class="dfinput" value="${user.username}"/> </li> <li> <label>性别</label><cite> <c:choose> <c:when test="${user.usersex == 1}"> <input name="usersex" type="radio" value="1" checked="checked" />男 <input name="usersex" type="radio" value="0" />女 </c:when> <c:otherwise> <input name="usersex" type="radio" value="1" />男 <input name="usersex" type="radio" value="0" checked="checked" />女 </c:otherwise> </c:choose>
</li> <li><label>手机号</label><input name="phonenumber" type="text" class="dfinput" value="${user.phonenumber}"/></li> <li><label>QQ号</label><input name="qqnumber" type="text" class="dfinput" value="${user.qqnumber}"/></li> <li><label> </label><input type="submit" class="btn" value="确认保存"/></li> </ul> </form> </div> </body> </html>
|
修改更新用户的servlet中的方法
package com.bjsxt.web.servlet;
import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService; import com.bjsxt.service.impl.UserManagerServiceImpl;
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.List;
@WebServlet("/userManager.do") public class UserManagerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("addUser".equals(flag)){ this.addUser(req,resp); }else if("findUser".equals(flag)){ this.findUser(req,resp); }else if("preUpdate".equals(flag)){ this.preUpdate(req,resp); }else if("modifyUser".equals(flag)){ this.modifyUser(req,resp); }else{ this.dropUser(req,resp); } } private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Users users = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.addUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } private Users createUsers(HttpServletRequest req){ String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); String usersex = req.getParameter("usersex"); String phonenumber = req.getParameter("phonenumber"); String qqnumber = req.getParameter("qqnumber"); Users users = new Users(); users.setQqnumber(qqnumber); users.setPhonenumber(phonenumber); users.setUsername(username); users.setUserpwd(userpwd); users.setUsersex(usersex); return users; }
private void findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ Users user = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); List<Users> list = userManagerService.findUser(user); req.setAttribute("list",list); req.getRequestDispatcher("usermanager/viewUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void preUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); Users user = userManagerService.findUserByUserId(Integer.parseInt(userid)); req.setAttribute("user",user); req.getRequestDispatcher("usermanager/updateUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); Users users = this.createUsers(req); users.setUserid(Integer.parseInt(userid)); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.modifyUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
6 删除用户业务
6.1 创建删除用户持久层
package com.bjsxt.dao;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerDao { void insertUser(Users users); List<Users> selectUsersByProperty(Users users); Users selectUserByUserId(int userid); void updateUserByUserId(Users users); void deleteUserByUserId(int userid); }
|
package com.bjsxt.dao.impl;
import com.bjsxt.commons.JdbcUtils; import com.bjsxt.dao.UserManagerDao; import com.bjsxt.pojo.Users;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;
public class UserManagerDaoImpl implements UserManagerDao {
@Override public void insertUser(Users users) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("insert into users values(default,?,?,?,?,?)"); ps.setString(1,users.getUsername()); ps.setString(2,users.getUserpwd()); ps.setString(3,users.getUsersex()); ps.setString(4,users.getPhonenumber()); ps.setString(5,users.getQqnumber()); ps.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally{ JdbcUtils.closeConnection(conn); } }
@Override public List<Users> selectUsersByProperty(Users users) { Connection conn = null; List<Users> list = new ArrayList<>(); try{ conn = JdbcUtils.getConnection(); String sql = this.createSQL(users); PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ Users user = new Users(); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUsersex(resultSet.getString("usersex")); list.add(user); } }catch(Exception e){ e.printStackTrace(); }finally{ JdbcUtils.closeConnection(conn); } return list; }
@Override public Users selectUserByUserId(int userid) { Connection conn = null; Users user = null; try{ conn = JdbcUtils.getConnection(); PreparedStatement preparedStatement = conn.prepareStatement("select * from users where userid = ?"); preparedStatement.setInt(1,userid); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()){ user = new Users(); user.setUserid(resultSet.getInt("userid")); user.setPhonenumber(resultSet.getString("phonenumber")); user.setQqnumber(resultSet.getString("qqnumber")); user.setUserpwd(resultSet.getString("userpwd")); user.setUsername(resultSet.getString("username")); user.setUsersex(resultSet.getString("usersex")); } }catch(Exception e){ e.printStackTrace(); }finally{ JdbcUtils.closeConnection(conn); } return user; }
@Override public void updateUserByUserId(Users users) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement preparedStatement = conn.prepareStatement("update users set username=? ,usersex = ?,phonenumber=?,qqnumber = ? where userid = ? "); preparedStatement.setString(1,users.getUsername()); preparedStatement.setString(2,users.getUsersex()); preparedStatement.setString(3,users.getPhonenumber()); preparedStatement.setString(4,users.getQqnumber()); preparedStatement.setInt(5,users.getUserid()); preparedStatement.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally { JdbcUtils.closeConnection(conn); } }
@Override public void deleteUserByUserId(int userid) { Connection conn = null; try{ conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); PreparedStatement ps = conn.prepareStatement("delete from users where userid = ?"); ps.setInt(1,userid); ps.execute(); conn.commit(); }catch(Exception e){ e.printStackTrace(); JdbcUtils.rollbackConnection(conn); }finally{ JdbcUtils.closeConnection(conn); } }
private String createSQL(Users users){ StringBuffer stringBuffer = new StringBuffer("select * from users where 1=1 "); if(users.getUsersex() != null && users.getUsersex().length() > 0){ stringBuffer.append(" and usersex = "+users.getUsersex()); } if(users.getQqnumber() != null && users.getQqnumber().length() > 0){ stringBuffer.append(" and qqnumber = "+users.getQqnumber()); } if(users.getUsername() != null && users.getUsername().length() > 0){ stringBuffer.append(" and username = "+users.getUsername()); } if(users.getPhonenumber() != null &&users.getPhonenumber().length() > 0){ stringBuffer.append(" and phonenumber = "+users.getPhonenumber()); } return stringBuffer.toString(); } }
|
6.2 创建删除用户业务层
package com.bjsxt.service;
import com.bjsxt.pojo.Users;
import java.util.List;
public interface UserManagerService { void addUser(Users users); List<Users> findUser(Users users); Users findUserByUserId(int userid); void modifyUser(Users users); void dropUser(int userid); }
|
package com.bjsxt.service.impl;
import com.bjsxt.dao.UserManagerDao; import com.bjsxt.dao.impl.UserManagerDaoImpl; import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService;
import java.util.List;
public class UserManagerServiceImpl implements UserManagerService {
@Override public void addUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.insertUser(users); }
@Override public List<Users> findUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); return userManagerDao.selectUsersByProperty(users); }
@Override public Users findUserByUserId(int userid) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); return userManagerDao.selectUserByUserId(userid); }
@Override public void modifyUser(Users users) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.updateUserByUserId(users); }
@Override public void dropUser(int userid) { UserManagerDao userManagerDao = new UserManagerDaoImpl(); userManagerDao.deleteUserByUserId(userid); } }
|
6.3 创建删除用户Servlet
package com.bjsxt.web.servlet;
import com.bjsxt.pojo.Users; import com.bjsxt.service.UserManagerService; import com.bjsxt.service.impl.UserManagerServiceImpl;
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.List;
@WebServlet("/userManager.do") public class UserManagerServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String flag = req.getParameter("flag"); if("addUser".equals(flag)){ this.addUser(req,resp); }else if("findUser".equals(flag)){ this.findUser(req,resp); }else if("preUpdate".equals(flag)){ this.preUpdate(req,resp); }else if("modifyUser".equals(flag)){ this.modifyUser(req,resp); }else{ this.dropUser(req,resp); } } private void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Users users = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.addUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } private Users createUsers(HttpServletRequest req){ String username = req.getParameter("username"); String userpwd = req.getParameter("userpwd"); String usersex = req.getParameter("usersex"); String phonenumber = req.getParameter("phonenumber"); String qqnumber = req.getParameter("qqnumber"); Users users = new Users(); users.setQqnumber(qqnumber); users.setPhonenumber(phonenumber); users.setUsername(username); users.setUserpwd(userpwd); users.setUsersex(usersex); return users; }
private void findUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ Users user = this.createUsers(req); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); List<Users> list = userManagerService.findUser(user); req.setAttribute("list",list); req.getRequestDispatcher("usermanager/viewUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void preUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); Users user = userManagerService.findUserByUserId(Integer.parseInt(userid)); req.setAttribute("user",user); req.getRequestDispatcher("usermanager/updateUser.jsp").forward(req,resp); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); Users users = this.createUsers(req); users.setUserid(Integer.parseInt(userid)); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.modifyUser(users); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } }
private void dropUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String userid = req.getParameter("userid"); try{ UserManagerService userManagerService = new UserManagerServiceImpl(); userManagerService.dropUser(Integer.parseInt(userid)); resp.sendRedirect("ok.jsp"); }catch(Exception e){ e.printStackTrace(); resp.sendRedirect("error.jsp"); } } }
|
6.4 修改viewUser.jsp页面完成用户删除
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/6/2 0002 Time: 19:04 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" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head>
<body>
<div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="#">用户管理</a></li> <li><a href="#">查询用户</a></li> <li><a href="#">查询结果</a></li> </ul> </div>
<div class="rightinfo">
<div class="formtitle1"><span>用户列表</span></div>
<table class="tablelist" > <thead> <tr> <th>序号</th> <th>用户名</th> <th>用户性别</th> <th>手机号</th> <th>QQ号</th> <th>操作</th> </tr> </thead>
<tbody> <c:forEach items="${list}" var="user" varStatus="status"> <tr> <td>${status.count}</td> <td>${user.username}</td> <td> <c:choose> <c:when test="${user.usersex == 1}"> 男 </c:when> <c:otherwise> 女 </c:otherwise> </c:choose> </td> <td>${user.phonenumber}</td> <td>${user.qqnumber}</td> <td><a href="userManager.do?flag=preUpdate&userid=${user.userid}" class="tablelink">修改</a> <a href="userManager.do?userid=${user.userid}" class="tablelink click"> 删除</a></td> </tr> </c:forEach> </tbody> </table>
<div class="tip"> <div class="tiptop"><span>提示信息</span><a></a></div>
<div class="tipinfo"> <span><img src="images/ticon.png" /></span> <div class="tipright"> <p>是否确认对信息的修改 ?</p> <cite>如果是请点击确定按钮 ,否则请点取消。</cite> </div> </div>
<div class="tipbtn"> <input name="" type="button" class="sure" value="确定" /> <input name="" type="button" class="cancel" value="取消" /> </div>
</div>
</div> </body> </html>
|
PROJECT LINK:
https://www.aliyundrive.com/s/9JrLkf48XLd