三层架构
- web层
- 业务逻辑层
- 数据访问层
目录结构
环境搭建
1.创建javaweb项目
2.WEB-INF/lib下导入依赖jar包
3.前端框架导入(js,css,fonts文件夹)
4.src下 dao文件夹存放 数据访问层的 接口和实现类
5.service文件夹存放 业务逻辑层的 接口和实现类
6.web文件夹存放 web层的 servlet 和 其他
7.domain文件夹下存放 javaBean类
8.util文件夹下存放 工具类
9.src目录下存放JDBC连接池配置文件
项目截图:
功能简介
1. 用户登录
1.1 jsp页面代码
login.jsp页面
<%@ 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() { //获取图片元素 var 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>
1.2 Servlet 文件夹下代码
LoginServlet 页面
package cn.rg.web.servlet; import cn.rg.domain.User; import cn.rg.serivice.UserService; import cn.rg.serivice.impl.UserServiceImpl; 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 { //1.设置编码 request.setCharacterEncoding("utf-8"); //2.获取数据 //2.1获取用户填写的验证码 String verifycode = request.getParameter("verifycode"); //3.验证码校验 HttpSession session = request.getSession(); String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER"); session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性 //4.封装User对象 if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(verifycode)) { //验证码不正确 //提示信息 request.setAttribute("login_msg", "验证码错误!"); //跳转至登录界面 如果需要携带信息则使用转发,否则普通跳转使用重定向 request.getRequestDispatcher("/login.jsp").forward(request, response); return; } Map <String, String[]> map = request.getParameterMap(); //4.封装user对象 User user = new User(); try { BeanUtils.populate(user, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //5.调用service查询 UserServiceImpl service = new UserServiceImpl(); User loginUser = service.login(user); //6.判断是否登录成功 if (loginUser != null) { //登录成功 //将用户名存入session session.setAttribute("user", loginUser); response.sendRedirect(request.getContextPath() + "/index.jsp"); } else { //登录失败 跳回登录界面,由于前后两个页面一样所以可以用转发. request.setAttribute("login_msg", "用户名或密码错误"); request.getRequestDispatcher("/login.jsp").forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
CheckCodeServlet代码
package cn.rg.web.servlet; 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("/checkCodeServlet") public class CheckCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //服务器通知浏览器不要缓存 response.setHeader("pragma", "no-cache"); response.setHeader("cache-control", "no-cache"); response.setHeader("expires", "0"); //在内存中创建一个长80,宽30的图片,默认黑色背景 //参数一:长 //参数二:宽 //参数三:颜色 int width = 80; int height = 30; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //获取画笔 Graphics g = image.getGraphics(); //设置画笔颜色为灰色 g.setColor(Color.GRAY); //填充图片 g.fillRect(0, 0, width, height); //产生4个随机验证码,12Ey String checkCode = getCheckCode(); //将验证码放入HttpSession中 request.getSession().setAttribute("CHECKCODE_SERVER", checkCode); //设置画笔颜色为黄色 g.setColor(Color.YELLOW); //设置字体的小大 g.setFont(new Font("黑体", Font.BOLD, 24)); //向图片上写入验证码 g.drawString(checkCode, 15, 25); //将内存中的图片输出到浏览器 //参数一:图片对象 //参数二:图片的格式,如PNG,JPG,GIF //参数三:图片输出到哪里去 ImageIO.write(image, "PNG", response.getOutputStream()); } /** * 产生4位随机字符串 */ private String getCheckCode() { String base = "0123456789ABCDEFGabcdefg"; int size = base.length(); Random r = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 1; i <= 4; i++) { //产生0到size-1的随机值 int index = r.nextInt(size); //在base字符串中获取下标为index的字符 char c = base.charAt(index); //将c放入到StringBuffer中去 sb.append(c); } return sb.toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
1.3 service文件夹下代码
UserService代码
package cn.rg.serivice; import cn.rg.domain.PageBean; import cn.rg.domain.User; import java.util.List; import java.util.Map; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * * @return */ public List <User> findAll(); User login(User user); /** * 添加用户信息 * * @param user */ void add(User user); /** * 删除用户 * @param id */ void deleteUser(String id); /** * 通过id查找用户 * @param id * @return */ User findUserById(String id); /** * 更新User * @param user */ void updateUser(User user); /** * 删除选中的Users * @param uids */ void deleteSelectedUsers(String[] uids); /** * 分页条件查询(添加条件查询后) * @param currentPage * @param rows * @param conditions * @return */ PageBean<User> findUserByPage(String currentPage, String rows, Map <String, String[]> conditions); /** * 分页条件查询(1.0) * @param currentPage * @param rows * @return */ PageBean<User> findUserByPage(String currentPage, String rows); }
UserServiceImpl代码
package cn.rg.serivice.impl; import cn.rg.dao.UserDao; import cn.rg.dao.impl.UserDaoImpl; import cn.rg.domain.PageBean; import cn.rg.domain.User; import cn.rg.serivice.UserService; import java.util.List; import java.util.Map; public class UserServiceImpl implements UserService { private UserDao dao = new UserDaoImpl(); @Override public List <User> findAll() { //调用DAO完成查询 return dao.findAll(); } @Override public User login(User user) { //User user1 = dao.findUserByusernameAndPassword(user.getUsername(), user.getPassword()); return dao.findUserByusernameAndPassword(user.getUsername(), user.getPassword()); } @Override public void add(User user) { dao.add(user); } @Override public void deleteUser(String id) { dao.deleteById(Integer.parseInt(id)); } @Override public User findUserById(String id) { User user = dao.findById(Integer.parseInt(id)); return user; } @Override public void updateUser(User user) { dao.update(user); } @Override public void deleteSelectedUsers(String[] uids) { if(uids==null||uids.length<=0){ return; } for(int i = 0; i < uids.length; i++){ dao.deleteById(Integer.parseInt(uids[i])); } } @Override public PageBean <User> findUserByPage(String _currentPage, String _rows, Map <String, String[]> conditions) { //1.创建空的PageBean对象 PageBean <User> pb = new PageBean <>(); int currentPage = Integer.parseInt(_currentPage); int rows = Integer.parseInt(_rows); if(currentPage<1){ currentPage = 1; } //2.设置当前页面属性和rows属性 pb.setCurrentPage(currentPage); pb.setRows(rows); //3.调用DAO查询totalCount总记录数 UserDao dao = new UserDaoImpl(); //int totalCount = dao.findTotalCount(); int totalCount = dao.findTotalCount(conditions); pb.setTotalCount(totalCount); //4.计算start int start = (currentPage-1) * rows; //5.返回DAO查询的list集合 List<User> list =dao.findByPage(start,rows,conditions); pb.setList(list); //6.计算总页码 int totalPage = (totalCount % rows == 0) ? totalCount / rows :(totalCount / rows +1); pb.setTotalPage(totalPage); return pb; } @Override public PageBean <User> findUserByPage(String _currentPage, String _rows) { //1.创建空的PageBean对象 PageBean <User> pb = new PageBean <>(); int currentPage = Integer.parseInt(_currentPage); int rows = Integer.parseInt(_rows); if(currentPage<1){ currentPage = 1; } //2.设置当前页面属性和rows属性 pb.setCurrentPage(currentPage); pb.setRows(rows); //3.调用DAO查询totalCount总记录数 UserDao dao = new UserDaoImpl(); int totalCount = dao.findTotalCount(); pb.setTotalCount(totalCount); //4.计算start int start = (currentPage-1) * rows; //5.返回DAO查询的list集合 List<User> list =dao.findByPage(start,rows); pb.setList(list); //6.计算总页码 int totalPage = (totalCount % rows == 0) ? totalCount / rows :(totalCount / rows +1); pb.setTotalPage(totalPage); return pb; } }
1.4dao文件夹下代码
UserDao.interface代码
package cn.rg.dao; import cn.rg.domain.User; import java.util.List; import java.util.Map; public interface UserDao { public List <User> findAll(); public User findUserByusernameAndPassword(String username, String password); void add(User user); /** * 删除用户通过id * @param id */ void deleteById(int id); /** * 通过id查找用户 * @param id */ User findById(int id); /** * 更新User * @param user */ void update(User user); /** * 查询所有的User记录数 * @return */ int findTotalCount(); /** * 查询所有的User记录数(条件查询) * @param conditions * @return */ int findTotalCount(Map<String, String[]> conditions); /** * 分页查询,返回该页的记录list * @param start * @param rows * @return */ List<User> findByPage(int start, int rows); List<User> findByPage(int start, int rows, Map<String, String[]> conditions); }
UserDaoImpl.java代码
package cn.rg.dao.impl; import cn.rg.dao.UserDao; import cn.rg.domain.User; import cn.rg.util.JDBCUtils; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class UserDaoImpl implements UserDao { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); @Override public List <User> findAll() { //使用JDBC操作数据库 String sql = "select * from user"; List <User> users = template.query(sql, new BeanPropertyRowMapper <User>(User.class)); return users; } @Override public User findUserByusernameAndPassword(String username, String password) { try { String sql = "select * from user where username = ? and password = ?"; User user = template.queryForObject(sql, new BeanPropertyRowMapper <User>(User.class), username, password); return user; } catch (Exception e)//这里用的找这样写吗? { e.printStackTrace(); return null; } } @Override public void add(User user) { String sql = "insert into user values(null,?,?,?,?,?,?,null,null)"; template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail()); } @Override public void deleteById(int id) { String sql = "delete from user where id = ?"; template.update(sql,id); } @Override public User findById(int id) { String sql = "select * from user where id = ?"; return template.queryForObject(sql, new BeanPropertyRowMapper <User>(User.class), id); } @Override public void update(User user) { String sql = "UPDATE USER SET gender= ? ,age= ? ,address= ? ,qq= ? ,email= ? WHERE id = ?"; template.update(sql,user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId()); } @Override public int findTotalCount() { String sql = "select count(*) from user"; return template.queryForObject(sql,Integer.class); } @Override public int findTotalCount(Map <String, String[]> conditions) { //1.定义模板初始化sql String sql = "select count(*) from user where 1 = 1 "; StringBuilder sb = new StringBuilder(sql); //2.遍历map Set <String> keySet = conditions.keySet(); List <Object> params = new ArrayList <>(); for (String key : keySet) { //排除分页条件参数 if("currentPage".equals(key)||"rows".equals(key)||"totalPage".equals(key)){ continue; } String value = conditions.get(key)[0];//由于我们的输入框的值都是只有一个,所以直接拿取第一个值就行. //判断value是否合法 if(value!=null && !"".equals(value)){ sb.append(" and "+key+" like ? "); params.add("%"+value+"%"); } } //System.out.println(sb.toString()); //System.out.println(params); return template.queryForObject(sb.toString(),Integer.class,params.toArray()); } @Override public List <User> findByPage(int start, int rows) { String sql = "select * from user limit ?,? "; return template.query(sql,new BeanPropertyRowMapper <User>(User.class),start,rows); /*List <User> list = template.queryForList(sql, User.class, start, rows); return list;*/ } @Override public List <User> findByPage(int start, int rows, Map <String, String[]> conditions) { String sql = "select * from user where 1 = 1 "; StringBuilder sb = new StringBuilder(sql); //2.遍历map Set <String> keySet = conditions.keySet(); List <Object> params = new ArrayList <>(); for (String key : keySet) { //排除分页条件参数 if("currentPage".equals(key)||"rows".equals(key)||"totalPage".equals(key)){ continue; } String value = conditions.get(key)[0];//由于我们的输入框的值都是只有一个,所以直接拿取第一个值就行. //判断value是否合法 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(); // System.out.println("user查询语句:"+sql); // System.out.println(params); return template.query(sql,new BeanPropertyRowMapper <User>(User.class),params.toArray()); } }
2.增加用户信息
图解:
网络异常,图片无法展示
|
2.1 jsp页面
add.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <!-- 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="get"> <div class="form-group"> <label for="name">姓名:</label> <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名"> </div> <div class="form-group"> <label>性别:</label> <input type="radio" name="gender" value="男" checked="checked"/>男 <input type="radio" name="gender" value="女"/>女 </div> <div class="form-group"> <label for="age">年龄:</label> <input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄"> </div> <div class="form-group"> <label for="address">籍贯:</label> <select name="address" class="form-control" id="address"> <option value="陕西">陕西</option> <option value="北京">北京</option> <option value="上海">上海</option> </select> </div> <div class="form-group"> <label for="qq">QQ:</label> <input type="text" class="form-control" id="qq" name="qq" placeholder="请输入QQ号码"/> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱地址"/> </div> <div class="form-group" style="text-align: center"> <input class="btn btn-primary" type="submit" value="提交"/> <input class="btn btn-default" type="reset" value="重置"/> <input class="btn btn-default" type="button" value="返回"/> </div> </form> </div> </body> </html>
2.2 Servlet文件下的代码
AddUserServlet页面代码
package cn.rg.web.servlet; import cn.rg.domain.User; import cn.rg.serivice.UserService; import cn.rg.serivice.impl.UserServiceImpl; 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 java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/addUserServlet") public class AddUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); Map <String, String[]> map = request.getParameterMap(); User user = new User(); try { BeanUtils.populate(user, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } UserService service = new UserServiceImpl(); service.add(user); response.sendRedirect(request.getContextPath()+"/userListServlet"); //response.sendRedirect("${pageContext.request.contextPath}/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
3.修改用户信息
图解
网络异常,图片无法展示
|
3.1 JSP页面
Update.jsp
<%@ 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" value="${user.id}" name="id"> <div class="form-group"> <label for="name">姓名:</label> <input type="text" class="form-control" id="name" value="${user.name}" name="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" value="${user.age}" id="age" name="age" placeholder="请输入年龄"/> </div> <div class="form-group"> <label for="address">籍贯:</label> <select name="address" class="form-control"> <c:if test="${user.address=='广东'}"> <option value="广东" selected>广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> </c:if> <c:if test="${user.address=='广西'}"> <option value="广东" >广东</option> <option value="广西" selected>广西</option> <option value="湖南">湖南</option> </c:if> <c:if test="${user.address=='湖南'}"> <option value="广东" >广东</option> <option value="广西">广西</option> <option value="湖南" selected>湖南</option> </c:if> </select> </div> <div class="form-group"> <label for="qq">QQ:</label> <input type="text" class="form-control" value="${user.qq}" id="qq" name="qq" /> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" value="${user.email}" name="email" id="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.2Servlet页面
- FindUserServlet:查询要修改用户的信息(用于在修改页面进行显示)
package cn.rg.web.servlet; import cn.rg.domain.User; import cn.rg.serivice.UserService; import cn.rg.serivice.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; @WebServlet("/findUserServlet") public class FindUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); UserService service = new UserServiceImpl(); User user = service.findUserById(id); request.setAttribute("user",user); request.getRequestDispatcher("/update.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
- UpdateUserServlet
package cn.rg.web.servlet; import cn.rg.domain.User; import cn.rg.serivice.UserService; import cn.rg.serivice.impl.UserServiceImpl; 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 java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/updateUserServlet") public class UpdateUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); Map <String, String[]> map = request.getParameterMap(); User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } UserService service = new UserServiceImpl(); // User user1 = new User(); // user1.setGender("男"); // user1.setAge(66); // user1.setAddress("广东"); // user1.setQq("123456798"); // user1.setEmail("haha@qq.com"); service.updateUser(user); `在这里插入代码片`response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
4.删除用户信息
图解
删除单个
网络异常,图片无法展示
|
删除选中:
网络异常,图片无法展示
|
4.1 Servlet页面
每次删除单个
DeleteUserServlet
package cn.rg.web.servlet; import cn.rg.serivice.UserService; import cn.rg.serivice.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 javax.xml.ws.Service; import java.io.IOException; import java.util.Map; @WebServlet("/delUserServlet") public class DelUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Map <String, String[]> conditions = request.getParameterMap(); String id = request.getParameter("id"); UserService service = new UserServiceImpl(); service.deleteUser(id); response.sendRedirect(request.getContextPath()+"/findUserByPageServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
DelSelectedUserServlet 删除选中多个
package cn.rg.web.servlet; import cn.rg.serivice.UserService; import cn.rg.serivice.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; @WebServlet("/delSelectedUserServlet") public class DelSelectedUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] uids = request.getParameterValues("uid"); UserService service = new UserServiceImpl(); service.deleteSelectedUsers(uids); response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
5.分页查询用户信息
图解
网络异常,图片无法展示
|
网络异常,图片无法展示
|
5.1 jsp页面
list.jsp页面
<%@ 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"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> function deleteUser(id) { if(confirm("确定删除吗?")){ //alert("hahhah"); location.href="${pageContext.request.contextPath}/delUserServlet?id="+id; } } window.onload = function () { document.getElementById('delselected').onclick = function () {//点击删除全部进行提交 if(confirm("确认删除选中的记录吗?")){ var flag = false;//判断选中的是否有记录. var cbs = document.getElementsByName('uid'); for(var i = 0; i < cbs.length; i++){ if(cbs[i].checked){ flag = true; break; } } if(flag){ document.getElementById('form').submit(); } } } document.getElementById('selectAll').onclick = function () {//点击全选和全不选. var cbs = document.getElementsByName('uid'); for(var i = 0; i < cbs.length; i++){ cbs[i].checked = this.checked; } } } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float:left;"> <form class="form-inline" method="post" action="${pageContext.request.contextPath}/findUserByPageServlet"> <div class="form-group"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2" value="${conditions.name[0]}" name="name"> </div> <div class="form-group"> <label for="exampleInputPlace2">籍贯</label> <input type="text" class="form-control" id="exampleInputPlace2" value="${conditions.address[0]}" name="address"> </div> <div class="form-group"> <label for="exampleInputEmail2">邮箱</label> <input type="text" class="form-control" id="exampleInputEmail2" value="${conditions.email[0]}" name="email"> </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right; margin: 8px"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <a class="btn btn-primary" href="javascript:void(0);" id="delselected">删除选中</a> </div> <form action="${pageContext.request.contextPath}/delSelectedUserServlet" method="post" id="form"> <table border="1" class="table table-bordered table-hover" > <tr class="success"> <td><input type="checkbox" id="selectAll"></td> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach items="${pb.list}" var="user" varStatus="s"> <tr> <td><input type="checkbox" name="uid" value="${user.id}"></td> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a> <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td> </tr> </c:forEach> </table> </form> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <c:if test="${pb.currentPage==1}"><%--如果当前的currentpage已经到了边界,则禁用向左点击的按钮--%> <li class="disabled"> </c:if> <c:if test="${pb.currentPage!=1}"> <li > </c:if> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage-1}&rows=5&name=${conditions.name[0]}&address=${conditions.address[0]}&email=${conditions.email[0]}" aria-label="Previous"><%--向前点击,页码-1--%> <span aria-hidden="true">«</span> </a> </li> <c:forEach var="i" begin="1" end="${pb.totalPage}" step="1"> <c:if test="${pb.currentPage==i}"><%--对当前所在页面的页码进行激活处理.--%> <li class="active"> </c:if> <c:if test="${pb.currentPage!=i}"> <li> </c:if> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${conditions.name[0]}&address=${conditions.address[0]}&email=${conditions.email[0]}">${i}</a></li> </c:forEach> <c:if test="${pb.currentPage==pb.totalPage}"> <li class="disabled"> </c:if> <c:if test="${pb.currentPage!=pb.totalPage}"> <li > </c:if> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage+1}&rows=5&totalPage=${pb.totalPage}&name=${conditions.name[0]}&address=${conditions.address[0]}&email=${conditions.email[0]}" aria-label="Next"><%--向后点击,页码+1--%> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px; margin-left: 8px">共${pb.totalCount}条记录,共${pb.totalPage}页</span> </ul> </nav> </div> </div> </body> </html>
6.复杂条件查询用户信息
网络异常,图片无法展示
|
6.1 Servlet 页面
FindUserByPageServlet
中间有个findUserByPage重载,分别是使用复杂条件查询和不使用复杂条件查询.
另外要注意,再进行复杂条件查询书写时,必须要进行参数传递.
package cn.rg.web.servlet; import cn.rg.domain.PageBean; import cn.rg.domain.User; import cn.rg.serivice.UserService; import cn.rg.serivice.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 { //1.获取请求参数currentPage,rows request.setCharacterEncoding("utf-8"); String currentPage = request.getParameter("currentPage"); String rows = request.getParameter("rows"); String totalPage = request.getParameter("totalPage"); Map <String, String[]> conditions = request.getParameterMap(); if(currentPage==null||"".equals(currentPage)){//如果currentPage或者rows为空则设定一个默认值.这样就可以处理进入时的问题. currentPage = "1"; } if(rows==null||"".equals(rows)){ rows = "5"; } if(Integer.parseInt(currentPage)<1){/*如果已经到首页,用户仍然进行了点击,则会导致currentPage<1,则将currentPage置为1*/ currentPage = "1"; } if(totalPage!=null&&totalPage!=""&&Integer.parseInt(currentPage)>Integer.parseInt(totalPage)){ currentPage = totalPage;/*如果已经到了尾页,用户仍然进行点击则会导致,currentPage超出最大页,则将currentPage置为最大页数即可*/ } //2.调用Service查询PageBean UserService service = new UserServiceImpl(); PageBean<User> pb = service.findUserByPage( currentPage, rows); System.out.println(conditions.size()); //PageBean<User> pb = service.findUserByPage( currentPage, rows,conditions); System.out.println(pb); //3.将PageBean存入到request request.setAttribute("pb",pb); request.setAttribute("conditions",conditions);//将查询内容进行回显 //4.转发到list.jsp展示 request.getRequestDispatcher("/list.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
7.登录后的主页面
7.1 JSP页面
index.jsp
<%@ 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"> </script> </head> <body> <div> ${user.name},欢迎你! </div> <div align="center"> <a href="${pageContext.request.contextPath}/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息 </a> </div> </body> </html>
7.2Servlet页面
UserListServlet:显示所有的用户信息到表格.
package cn.rg.web.servlet; import cn.rg.domain.User; import cn.rg.serivice.UserService; import cn.rg.serivice.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.List; @WebServlet("/userListServlet") public class UserListServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.调用UserService完成查询 UserService service = new UserServiceImpl(); List <User> users = service.findAll(); //2.将list存入request域 request.setAttribute("users", users); //转发到list.jsp request.getRequestDispatcher("/list.jsp").forward(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }