黑马第1个案例 登录验证 增删改查 条件查询+分页

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jie
 4   Date: 2019/5/12
 5   Time: 9:01
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
10 
11 
12 
13     
14     
15     
16     管理员登录
17 
18     
19     
20     
21     
22     
23     
24     
36 
37 
38 
class="container" style="width: 400px;"> 39

管理员登录

40
41
class="form-group"> 42 43 class="form-control" id="user" placeholder="请输入用户名"/> 44
45 46
class="form-group"> 47 48 class="form-control" id="password" placeholder="请输入密码"/> 49
50 51
class="form-inline"> 52 53 class="form-control" id="verifycode" maxlength="4" placeholder="请输入验证码" style="width: 120px;"/> 54 55
56
57
class="form-group" style="text-align: center;"> 58 class="btn btn btn-primary" type="submit" value="登录"> 59
60
61 62 63 if test="${loginMsg != null}"> 64
class="alert alert-warning alert-dismissible" role="alert"> 65 67 ${loginMsg} 68
69
if> 70
71 72
login.jsp
  1 <%--
  2   Created by IntelliJ IDEA.
  3   User: jie
  4   Date: 2019/5/10
  5   Time: 20:00
  6   To change this template use File | Settings | File Templates.
  7 --%>
  8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 10 
 11 
 12 
 13 
 14     
 15     
 16     
 17     
 18     
 21     
 22     
 23     用户信息管理系统
 24 
 25     
 26     
 27     
 28     
 29     
 30     
 31     
 68     
151 
152 
153 
class="container"> 154 155

用户信息列表

156 157 <%--
class="btn-group" role="group" aria-label="...">--%> 158 <%----%> 159 <%----%> 160 <%----%> 161 <%--
--%> 162
class="tool mb-10"> 163
class="form-inline float-left"> 164 165
class="form-group"> 166 167 class="form-control" id="name" name="name"> 168
169
class="form-group"> 170 171 class="form-control" value="${searchCondition.address[0]}" id="address" name="address"> 172
173
class="form-group"> 174 175 class="form-control" value="${searchCondition.email[0]}" id="email" name="email"> 176
177 178
179
class="right-tool float-right"> 180 class="btn btn-primary" href="add.jsp" role="button">添加联系人 181 class="btn btn-primary" href="javascript: submitDelSelected();" role="button">删除选中 182
183 <%----%> 184 <%----%> 185
186
187 class="table table-bordered table-hover"> 188class="success"> 189190191192193194195196197198199 200 201202203204205206207208209210211212
编号 姓名 性别 年龄 籍贯 QQ 邮箱 操作
${vs.count} ${user.name} ${user.gender} ${user.age} ${user.address} ${user.qq} ${user.email} class="btn btn-default btn-sm" href="/findUserServlet?id=${user.id}">修改 class="btn btn-default btn-sm" href="javascript: deleteUser(${user.id});">删除
213 214 257
258 259
List.jsp
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jie
 4   Date: 2019/5/10
 5   Time: 20:53
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 
10 
11 
12 
13 
14     
15     
16     
17     
18     
21     
22     
23     添加用户
24 
25     
26     
27     
28     
29     
30     
31     
40 
41 
42 
class="container"> 43

添加联系人页面

44
45
class="form-group"> 46 47 class="form-control" id="name" name="name" placeholder="请输入姓名"> 48
49 50
class="form-group"> 51 52 53 54
55 56
class="form-group"> 57 58 class="form-control" id="age" name="age" placeholder="请输入年龄"> 59
60 61
class="form-group"> 62 63 68
69 70
class="form-group"> 71 72 class="form-control" name="qq" placeholder="请输入QQ号码"/> 73
74 75
class="form-group"> 76 77 class="form-control" name="email" placeholder="请输入邮箱地址"/> 78
79 80
class="form-group" style="text-align: center"> 81 class="btn btn-primary" type="submit" value="提交" /> 82 class="btn btn-default" type="reset" value="重置" /> 83 class="btn btn-default" type="button" value="返回" /> 84 <%--class="btn btn-default" href="${pageContext.request.contextPath}/findUserByPageServlet" role="button">返回--%> 85
86
87
class="error"> 88 ${error} 89
90
91 96 97
add.jsp
  1 <%--
  2   Created by IntelliJ IDEA.
  3   User: jie
  4   Date: 2019/5/10
  5   Time: 22:13
  6   To change this template use File | Settings | File Templates.
  7 --%>
  8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 10 
 11 
 12 
 13 
 14     
 15     
 16     
 17     
 18     修改用户
 19 
 20     
 21     
 22     
 23     
 54 
 55 
 56 
class="container" style="width: 400px;"> 57

修改联系人

58
59 60
class="form-group"> 61 62 class="form-control" id="name" name="name" value="${user.name}"/> 63
64 65
class="form-group"> 66 67 68 <%--男--%> 69 <%--女--%> 70 71 if test="${user.gender == '男'}"> 72 73 74 if> 75 if test="${user.gender == '女'}"> 76 77 78 if> 79 if test="${user.gender != '女' && user.gender != '男'}"> 80 81 82 if> 83
84 85
class="form-group"> 86 87 class="form-control" id="age" value="${user.age}" name="age" placeholder="请输入年龄" /> 88
89 90
class="form-group"> 91 92 <%----%> 116 140
141 142
class="form-group"> 143 144 class="form-control" value="${user.qq}" name="qq" placeholder="请输入QQ号码"/> 145
146 147
class="form-group"> 148 149 class="form-control" value="${user.email}" name="email" placeholder="请输入邮箱地址"/> 150
151 152
class="form-group" style="text-align: center"> 153 class="btn btn-primary" type="submit" value="提交" /> 154 class="btn btn-default" type="reset" value="重置" /> 155 class="btn btn-default" type="button" value="返回"/> 156
157
158
159 164 165
update.jsp
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jie
 4   Date: 2019/5/9
 5   Time: 20:26
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 
10 
11 
12   
13   
14   
15   首页
16 
17   
18   
19   
20   
21   
22   
23   
25 
26 
27 
28 <a 29 href="/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息 30 31
32 33
index.jsp
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.impl.UserServiceImpl;
 5 import org.apache.commons.beanutils.BeanUtils;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import javax.servlet.http.HttpSession;
13 import java.io.IOException;
14 import java.lang.reflect.InvocationTargetException;
15 
16 @WebServlet("/loginServlet")
17 public class LoginServlet extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         /*
20             设置编码
21             校验验证码
22             获取参数
23             封装User
24             调用Service查询
25             判断是否登录成功
26          */
27         request.setCharacterEncoding("UTF-8");
28 
29         String verifycode = request.getParameter("verifycode");
30         HttpSession session = request.getSession();
31         String checkcodeSession = (String) session.getAttribute("CHECKCODE_SERVER");
32         session.removeAttribute("CHECKCODE_SERVER");
33         if(checkcodeSession == null || !checkcodeSession.equalsIgnoreCase(verifycode)){
34             //验证码不正确,给出提示信息,跳转到登录页面
35             request.setAttribute("loginMsg", "验证码错误");
36             request.getRequestDispatcher("/login.jsp").forward(request, response);
37             return;
38         }
39 
40         User loginCondition = new User();
41         try {
42             BeanUtils.populate(loginCondition, request.getParameterMap());
43         } catch (IllegalAccessException e) {
44             e.printStackTrace();
45         } catch (InvocationTargetException e) {
46             e.printStackTrace();
47         }
48 
49         UserServiceImpl userService = new UserServiceImpl();
50         User user = userService.login(loginCondition);
51         if(user != null){
52             request.getSession().setAttribute("user", user);
53             response.sendRedirect(request.getContextPath() + "/index.jsp");
54         }else{
55             //跳转到登录页面,给出用户名或密码错误提示
56             request.setAttribute("loginMsg", "用户名或密码错误");
57             request.getRequestDispatcher("/login.jsp").forward(request, response);
58         }
59     }
60 
61     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
62         doPost(request, response);
63     }
64 }
LoginServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.utils.GraphicHelper;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 
12 @WebServlet("/checkCodeServlet")
13 public class CheckCodeServlet extends HttpServlet {
14     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         String checkcode = GraphicHelper.create(80, 40, "jpg", response.getOutputStream());
16         request.getSession().setAttribute("CHECKCODE_SERVER", checkcode);
17     }
18 
19     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20         doPost(request, response);
21     }
22 }
CheckCodeServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.UserService;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.util.List;
14 
15 @WebServlet("/userListServlet")
16 public class UserListServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         //调用业务,获取所有用户
19         UserService userService = new UserServiceImpl();
20         List userList = userService.findAll();
21 
22         //存入request域,转发到list.jsp
23         request.setAttribute("userList", userList);
24         request.getRequestDispatcher("list.jsp").forward(request, response);
25     }
26 
27     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
28         doPost(request, response);
29     }
30 }
UserListServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.UserService;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 import org.apache.commons.beanutils.BeanUtils;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import java.io.IOException;
14 import java.lang.reflect.InvocationTargetException;
15 
16 @WebServlet("/addUserServlet")
17 public class AddUserServlet extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         /*
20         在AddServlet中:
21             获取表单参数并封装成对象User
22             调用业务添加用户,addUser(User):boolean
23             成功,重定向到userListServlet
24             (注意:如果使用转发,则地址为addServlet,用户刷新会出问题)
25             失败,直接转发回原来的add.jsp,给出错误消息
26          */
27         request.setCharacterEncoding("UTF-8");
28         //获取表单参数并封装成对象User
29         User user = new User();
30         try {
31             //如果传入了xxx作为年龄,不会传出异常,BeanUtils将数字解析异常吃掉了。并将整型赋值为0。
32             BeanUtils.populate(user, request.getParameterMap());
33         } catch (IllegalAccessException e) {
34             e.printStackTrace();
35         } catch (InvocationTargetException e) {
36             e.printStackTrace();
37         }
38 
39         //调用业务添加用户,addUser(User):boolean
40         UserService userService = new UserServiceImpl();
41         if(userService.add(user)){
42             //成功,重定向到userListServlet
43             response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
44         }else{
45             //失败,直接转发回原来的add.jsp,给出错误消息,有问题,永远不会出现失败。
46             request.setAttribute("error", "添加用户失败");
47             request.getRequestDispatcher("/add.jsp").forward(request, response);
48         }
49     }
50 
51     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
52         doPost(request, response);
53     }
54 }
AddUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.service.UserService;
 4 import cn.itcast.service.impl.UserServiceImpl;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import java.io.IOException;
12 
13 @WebServlet("/deleteServlet")
14 public class DeleteUserServlet extends HttpServlet {
15 
16     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         /*
18             在deleteServlet中:
19                 获取id,根据id,调用业务删除用户
20                 重定向到userListServlet页。
21          */
22         //获取id
23         String id = request.getParameter("id");
24 
25         //根据id,调用业务删除用户
26         UserServiceImpl userService = new UserServiceImpl();
27         userService.deleteById(id);
28 
29         //重定向到userListServlet页。
30         response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
31 
32         //使用转发,貌似没有出问题,除了用户列表的地址栏变为:http://localhost/deleteServlet?id=10
33 //        request.getRequestDispatcher("/findUserByPageServlet").forward(request, response);
34     }
35 
36     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
37         doPost(request, response);
38     }
39 }
DeleteUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.impl.UserServiceImpl;
 5 import org.apache.commons.beanutils.BeanUtils;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.lang.reflect.InvocationTargetException;
14 
15 @WebServlet("/findUserServlet")
16 public class FindUserServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         /*
19         在EditServlet中:
20             获取参数,封装User,存入request域,转发给update.jsp
21          */
22         String id = request.getParameter("id");
23 
24         UserServiceImpl userService = new UserServiceImpl();
25         User user = userService.findUserById(id);
26 
27         request.setAttribute("user", user);
28         request.getRequestDispatcher("/update.jsp").forward(request, response);
29     }
30 
31     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
32         doPost(request, response);
33     }
34 }
FindUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.UserService;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 import org.apache.commons.beanutils.BeanUtils;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import java.io.IOException;
14 import java.lang.reflect.InvocationTargetException;
15 
16 @WebServlet("/updateServlet")
17 public class UpdateUserServlet extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         /*
20         在updateServlet中:
21             获取表单数据,封装User对象。
22             调业务更新,void update(User)
23             转发到userListServlet
24          */
25         request.setCharacterEncoding("UTF-8");
26         //获取表单数据,封装User对象。
27         User user = new User();
28         try {
29             BeanUtils.populate(user, request.getParameterMap());
30         } catch (IllegalAccessException e) {
31             e.printStackTrace();
32         } catch (InvocationTargetException e) {
33             e.printStackTrace();
34         }
35         //调业务更新,void update(User)
36         UserService userService = new UserServiceImpl();
37         userService.update(user);
38 
39         //转发到userListServlet
40         response.sendRedirect("/findUserByPageServlet");
41     }
42 
43     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
44         doPost(request, response);
45     }
46 }
UpdateUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.service.impl.UserServiceImpl;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 
12 @WebServlet("/delSelectedServlet")
13 public class DelSelectedServlet extends HttpServlet {
14     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         /*
16             2.在DelSelectedServlet中
17                 获取选中的id
18                 调用业务,删除选中用户 deleteUsers(String ids[])
19                 转到,UserListServlet
20          */
21         //获取选中的id
22         String[] ids = request.getParameterValues("id");
23 
24         //调用业务,删除选中用户 deleteUsers(String ids[])
25         UserServiceImpl userService = new UserServiceImpl();
26         userService.deleteUsers(ids);
27 
28         //转到,UserListServlet
29         response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
30     }
31 
32     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
33         doPost(request, response);
34     }
35 }
DelSelectedServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.PageBean;
 4 import cn.itcast.domain.User;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.util.Map;
14 
15 @WebServlet("/findUserByPageServlet")
16 public class FindUserByPageServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         request.setCharacterEncoding("utf-8");
19         //获取页面参数
20         String currentPage = request.getParameter("currentPage");
21         String pageSize = request.getParameter("pageSize");
22 
23         Map searchCondition = request.getParameterMap();
24         //查询用户页的业务。
25         UserServiceImpl userService = new UserServiceImpl();
26         PageBean userPage = userService.findUserByPage(currentPage, pageSize, searchCondition);
27 
28         //转发给list.jsp
29         request.setAttribute("searchCondition", searchCondition);
30         request.setAttribute("userPage", userPage);
31         request.getRequestDispatcher("/list.jsp").forward(request, response);
32     }
33 
34     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35         doPost(request, response);
36     }
37 }
FindUserByPageServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.PageBean;
 4 import cn.itcast.domain.User;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.util.Map;
14 
15 @WebServlet("/findUserByPageServlet")
16 public class FindUserByPageServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         request.setCharacterEncoding("utf-8");
19         //获取页面参数
20         String currentPage = request.getParameter("currentPage");
21         String pageSize = request.getParameter("pageSize");
22 
23         Map searchCondition = request.getParameterMap();
24         //查询用户页的业务。
25         UserServiceImpl userService = new UserServiceImpl();
26         PageBean userPage = userService.findUserByPage(currentPage, pageSize, searchCondition);
27 
28         //转发给list.jsp
29         request.setAttribute("searchCondition", searchCondition);
30         request.setAttribute("userPage", userPage);
31         request.getRequestDispatcher("/list.jsp").forward(request, response);
32     }
33 
34     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35         doPost(request, response);
36     }
37 }
FindUserByPageServlet
 1 package cn.itcast.web.filter;
 2 
 3 import cn.itcast.domain.User;
 4 
 5 import javax.servlet.*;
 6 import javax.servlet.annotation.WebFilter;
 7 import javax.servlet.http.HttpServletRequest;
 8 import java.io.IOException;
 9 
10 @WebFilter("/*")
11 public class LoginFilter implements Filter {
12     public void destroy() {
13     }
14 
15     public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
16         HttpServletRequest request = (HttpServletRequest) req;
17         //放行登录相关资源
18         String uri = request.getRequestURI();
19         if(uri.contains("/css/") || uri.contains("/fonts/") || uri.contains("/js/")
20             || uri.contains("/loginServlet") || uri.contains("/login.jsp") || uri.contains("/checkCodeServlet")){
21             chain.doFilter(req, resp);
22             return;
23         }
24 
25         //判断是否登录
26         User user = (User) request.getSession().getAttribute("user");
27         if(user != null){
28             //已经登录,放行
29             chain.doFilter(req, resp);
30         }else{
31             //没有登录,转发到登录页面进行登录
32             req.setAttribute("loginMsg", "您还没有登录,请登录!");
33             req.getRequestDispatcher("/login.jsp").forward(req, resp);
34         }
35     }
36 
37     public void init(FilterConfig config) throws ServletException {
38 
39     }
40 
41 }
LoginFilter
 1 package cn.itcast.utils;
 2 
 3 import com.alibaba.druid.pool.DruidDataSourceFactory;
 4 
 5 import javax.sql.DataSource;
 6 import javax.xml.crypto.Data;
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 import java.sql.Connection;
10 import java.sql.SQLException;
11 import java.util.Properties;
12 
13 /**
14  * JDBC工具类 使用Durid连接池
15  */
16 public class JDBCUtils {
17 
18     private static DataSource ds ;
19 
20     static {
21 
22         try {
23             //1.加载配置文件
24             Properties pro = new Properties();
25             //使用ClassLoader加载配置文件,获取字节输入流
26             InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
27             pro.load(is);
28 
29             //2.初始化连接池对象
30             ds = DruidDataSourceFactory.createDataSource(pro);
31 
32         } catch (IOException e) {
33             e.printStackTrace();
34         } catch (Exception e) {
35             e.printStackTrace();
36         }
37     }
38 
39     /**
40      * 获取连接池对象
41      */
42     public static DataSource getDataSource(){
43         return ds;
44     }
45 
46 
47     /**
48      * 获取连接Connection对象
49      */
50     public static Connection getConnection() throws SQLException {
51         return  ds.getConnection();
52     }
53 }
JDBCUtils
 1 package cn.itcast.utils;
 2 
 3 import javax.imageio.ImageIO;
 4 import java.awt.*;
 5 import java.awt.image.BufferedImage;
 6 import java.io.IOException;
 7 import java.io.OutputStream;
 8 import java.util.Random;
 9 
10 public final class GraphicHelper {
11 
12     /**
13      * 以字符串形式返回生成的验证码,同时输出一个图片
14      *
15      * @param width
16      *            图片的宽度
17      * @param height
18      *            图片的高度
19      * @param imgType
20      *            图片的类型
21      * @param output
22      *            图片的输出流(图片将输出到这个流中)
23      * @return 返回所生成的验证码(字符串)
24      */
25     public static String create(final int width, final int height,
26                                 final String imgType, OutputStream output) {
27         StringBuffer sb = new StringBuffer();
28         Random random = new Random();
29 
30         BufferedImage image = new BufferedImage(width, height,
31                 BufferedImage.TYPE_INT_RGB);
32         Graphics graphic = image.getGraphics();
33         graphic.setColor(Color.getColor("F8F8F8"));
34         graphic.fillRect(0, 0, width, height);
35 
36         Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN,
37                 Color.RED, Color.BLACK, Color.ORANGE, Color.magenta,Color.darkGray,Color.pink };
38         // 在 "画板"上生成干扰线条 ( 40 是线条个数)
39         for (int i = 0; i < 40; i++) {
40             graphic.setColor(colors[random.nextInt(colors.length)]);
41             final int x = random.nextInt(width);
42             final int y = random.nextInt(height);
43             final int w = random.nextInt(20);
44             final int h = random.nextInt(20);
45             final int signA = random.nextBoolean() ? 1 : -1;
46             final int signB = random.nextBoolean() ? 1 : -1;
47             graphic.drawLine(x, y, x + w * signA, y + h * signB);
48         }
49         // 在 "画板"上绘制字母
50         graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
51         for (int i = 0; i < 4; i++) {
52             final int temp = random.nextInt(26) + 97;
53             String s = String.valueOf((char) temp);
54             sb.append(s);
55             graphic.setColor(colors[random.nextInt(colors.length)]);
56             graphic.drawString(s, i * (width / 4), height - (height / 3));
57         }
58         graphic.dispose();
59         try {
60             ImageIO.write(image, imgType, output);
61         } catch (IOException e) {
62             e.printStackTrace();
63         }
64         return sb.toString();
65     }
66 }
GraphicHelper
 1 package cn.itcast.service;
 2 
 3 import cn.itcast.domain.PageBean;
 4 import cn.itcast.domain.User;
 5 
 6 import java.util.List;
 7 import java.util.Map;
 8 
 9 /**
10  * 用户管理服务
11  */
12 public interface UserService {
13 
14     /**
15      * 查询所有用户
16      * @return 所有用户的List集合对象
17      */
18     List findAll();
19 
20     /**
21      * 根据id删除用户
22      * @param id 需要被删除的用户的id
23      */
24     void deleteById(String id);
25 
26     /**
27      * 添加用户
28      * @return 如果添加成功,返回true,否则返回false
29      */
30     boolean add(User user);
31 
32     /**
33      * 根据用户id,进行更新
34      * @param user 需要更新的用户
35      */
36     void update(User user);
37 
38     /**
39      * 根据id数组删除用户
40      * @param ids 需要被删除的多个用户的id集合
41      */
42     void deleteUsers(String[] ids);
43 
44     /**
45      * 根据当前页和页大小查询页
46      * @return
47      * @param currentPageStr
48      * @param pageSizeStr
49      * @param parameterMap
50      */
51     PageBean findUserByPage(String currentPageStr, String pageSizeStr, Map parameterMap);
52 
53     /**
54      * 根据id查询用户
55      * @return
56      */
57     User findUserById(String id);
58 
59     /**
60      *  用户登录
61      * @param loginCondition 用户名和密码
62      * @return
63      */
64     User login(User loginCondition);
65 }
UserService
 1 package cn.itcast.service.impl;
 2 
 3 import cn.itcast.dao.UserDao;
 4 import cn.itcast.dao.impl.UserDaoImpl;
 5 import cn.itcast.domain.PageBean;
 6 import cn.itcast.domain.User;
 7 import cn.itcast.service.UserService;
 8 
 9 import java.util.List;
10 import java.util.Map;
11 
12 public class UserServiceImpl implements UserService {
13     private UserDao userDao = new UserDaoImpl();
14 
15     @Override
16     public List findAll() {
17         return userDao.findAll();
18     }
19 
20     @Override
21     public void deleteById(String id) {
22         userDao.deleteById(Integer.parseInt(id));
23     }
24 
25     @Override
26     public boolean add(User user) {
27         return userDao.add(user) > 0 ? true : false;
28     }
29 
30     @Override
31     public void update(User user) {
32         userDao.update(user);
33     }
34 
35     @Override
36     public void deleteUsers(String[] ids) {
37         //健壮性判断
38         if(ids != null && ids.length > 0){
39             for (String id : ids) {
40                 userDao.deleteById(Integer.parseInt(id));
41             }
42         }
43     }
44 
45     @Override
46     public PageBean findUserByPage(String currentPageStr, String pageSizeStr, Map searchCondition) {
47         //currentPage和pageSize
48         int currentPage = currentPageStr == null || "".equals(currentPageStr)
49                             ? 1 : Integer.parseInt(currentPageStr);
50         int pageSize = pageSizeStr == null || "".equals(pageSizeStr)
51                         ? 3 : Integer.parseInt(pageSizeStr);
52         //查询总条数
53         int totalCount = (int) userDao.findTotalCount(searchCondition);
54         //如果总条数为0,怎么进行处理
55 
56         //总页数
57         int totalPage = totalCount % pageSize == 0
58                 ? totalCount / pageSize
59                 : totalCount / pageSize + 1;
60 
61         //注意:如果总条数为0的处理方式,当前页超出范围
62         if(currentPage > totalPage){
63             currentPage = totalPage;
64         }
65         if(currentPage < 1){
66             currentPage = 1;
67         }
68 
69         //查询数据
70         int start = (currentPage - 1) * pageSize;
71         List users = userDao.findUserByPage(start, pageSize, searchCondition);
72 
73         PageBean userPage = new PageBean<>();
74         userPage.setCurrentPage(currentPage);
75         userPage.setPageSize(pageSize);
76         userPage.setTotalPage(totalPage);
77         userPage.setTotalCount(totalCount);
78         userPage.setPageData(users);
79         return userPage;
80     }
81 
82     @Override
83     public User findUserById(String id) {
84         return userDao.findById(Integer.parseInt(id));
85     }
86 
87     @Override
88     public User login(User loginCondition) {
89         return userDao.findByUsernameAndPassword(loginCondition.getUsername(), loginCondition.getPassword());
90     }
91 }
UserServiceImpl
 1 package cn.itcast.dao;
 2 
 3 import cn.itcast.domain.User;
 4 
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 /**
 9  * 用户操作
10  */
11 public interface UserDao {
12     /**
13      * 查询所有用户
14      * @return
15      */
16     List findAll();
17 
18     /**
19      * 根据id删除用户
20      * @param id 被删除用户的id
21      */
22     void deleteById(int id);
23 
24     /**
25      *  添加用户
26      * @param user 被添加的用户
27      * @return
28      */
29     int add(User user);
30 
31     /**
32      * 根据用户id,进行用户修改
33      * @param user
34      */
35     void update(User user);
36 
37     /**
38      *  查询全部用户数量
39      * @return
40      * @param searchCondition
41      */
42     long findTotalCount(Map searchCondition);
43 
44     /**
45      * 查询用户分页
46      * @param start 起始行
47      * @param pageSize 最大数量
48      * @param searchCondition
49      * @return
50      */
51     List findUserByPage(int start, int pageSize, Map searchCondition);
52 
53     /**
54      * 根据id查询用户
55      * @param id
56      * @return
57      */
58     User findById(int id);
59 
60     /**
61      * 根据用户名和密码查询用户
62      * @param username
63      * @param password
64      * @return
65      */
66     User findByUsernameAndPassword(String username, String password);
67 }
UserDao
  1 package cn.itcast.dao.impl;
  2 
  3 import cn.itcast.dao.UserDao;
  4 import cn.itcast.domain.User;
  5 import cn.itcast.utils.JDBCUtils;
  6 import org.springframework.dao.DataAccessException;
  7 import org.springframework.jdbc.core.BeanPropertyRowMapper;
  8 import org.springframework.jdbc.core.JdbcTemplate;
  9 
 10 import java.util.ArrayList;
 11 import java.util.List;
 12 import java.util.Map;
 13 
 14 public class UserDaoImpl implements UserDao {
 15     private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
 16 
 17     @Override
 18     public int add(User user) {
 19         //写sql
 20         String sql = "insert into user(name, gender, age, address, qq, email) values(?,?,?,?,?,?) ";
 21         //添加用户
 22         return jdbcTemplate.update(sql, user.getName(), user.getGender(), user.getAge(),
 23                 user.getAddress(), user.getQq(), user.getEmail());
 24     }
 25 
 26     @Override
 27     public void deleteById(int id) {
 28         //写sql
 29         String sql = "delete from user where id=?";
 30         //根据id删除用户
 31         jdbcTemplate.update(sql, id);
 32     }
 33 
 34     @Override
 35     public void update(User user) {
 36         //写sql
 37         String sql = "update user set name=?, gender=?, age=?, address=?, qq=?, email=? where id=? ";
 38         //修改用户
 39         jdbcTemplate.update(sql, user.getName(), user.getGender(), user.getAge(),
 40                 user.getAddress(), user.getQq(), user.getEmail(), user.getId());
 41     }
 42 
 43     @Override
 44     public long findTotalCount(Map searchCondition) {
 45         StringBuilder sql = new StringBuilder();
 46         sql.append("select count(*) from user where 1=1 ");
 47 
 48         List params = new ArrayList<>();
 49         prepareConditionPart(searchCondition, sql, params);
 50 
 51         return jdbcTemplate.queryForObject(sql.toString(), Long.class, params.toArray());
 52     }
 53 
 54     @Override
 55     public List findUserByPage(int start, int pageSize, Map searchCondition) {
 56         StringBuilder sql = new StringBuilder();
 57         sql.append("select id, name, gender, age, address, qq, email from  user where 1=1 ");
 58 
 59         List params = new ArrayList<>();
 60         prepareConditionPart(searchCondition, sql, params);
 61 //        String[] name = searchCondition.get("name");
 62 //        if(name != null){
 63 //            sql.append(" and name like ? ");
 64 //            params.add("%"+name[0]+"%");
 65 //        }
 66 //
 67 //        String[] address = searchCondition.get("address");
 68 //        if(address != null){
 69 //            sql.append(" and address like ? ");
 70 //            params.add("%"+address[0]+"%");
 71 //        }
 72 //
 73 //        String[] email = searchCondition.get("email");
 74 //        if(email != null){
 75 //            sql.append(" and email like ? ");
 76 //            params.add("%"+email[0]+"%");
 77 //        }
 78 
 79         sql.append(" limit ?, ? ");
 80         params.add(start);
 81         params.add(pageSize);
 82 
 83         return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(User.class),
 84                 params.toArray());
 85     }
 86 
 87     private void prepareConditionPart(Map searchCondition, StringBuilder sql, List params) {
 88         String[] name = searchCondition.get("name");
 89         if (name != null && !"".equals(name[0])) {
 90             sql.append(" and name like ? ");
 91             params.add("%" + name[0] + "%");
 92         }
 93 
 94         String[] address = searchCondition.get("address");
 95         if (address != null && !"".equals(address[0])) {
 96             sql.append(" and address like ? ");
 97             params.add("%" + address[0] + "%");
 98         }
 99 
100         String[] email = searchCondition.get("email");
101         if (email != null && !"".equals(email[0])) {
102             sql.append(" and email like ? ");
103             params.add("%" + email[0] + "%");
104         }
105     }
106 
107     @Override
108     public List findAll() {
109         //写sql
110         String sql = "select id, name, gender, age, address, qq, email from user";
111         //查询
112         return jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class));
113     }
114 
115     @Override
116     public User findById(int id) {
117         String sql = "select id, name, gender, age, address, qq, email from user where id=?";
118         return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
119     }
120 
121     @Override
122     public User findByUsernameAndPassword(String username, String password) {
123         String sql = "select id, name, gender, age, address, qq, email from user where username=? and password=?";
124         User user = null;
125         try{
126             user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class),
127                     username, password);
128         }catch (DataAccessException e){
129             e.printStackTrace();
130         }
131         return user;
132     }
133 } 
     
    UserDaoImpl  
    
   
  1 package cn.itcast.domain;
  2 /*
  3 create table user(   -- 创建表
  4     id int primary key auto_increment,
  5     name varchar(20) not null,
  6     gender varchar(5),
  7     age int,
  8     address varchar(32),
  9     qq    varchar(20),
 10     email varchar(50)
 11 );
 12  */
 13 public class User {
 14     private Integer id;
 15     private String name;
 16     private String gender;
 17     private Integer age;
 18     private String address;
 19     private String qq;
 20     private String email;
 21 
 22     private String username;
 23     private String password;
 24 
 25 
 26 
 27     public User() {
 28     }
 29 
 30     public Integer getId() {
 31         return id;
 32     }
 33 
 34     public void setId(Integer id) {
 35         this.id = id;
 36     }
 37 
 38     public String getName() {
 39         return name;
 40     }
 41 
 42     public void setName(String name) {
 43         this.name = name;
 44     }
 45 
 46     public String getGender() {
 47         return gender;
 48     }
 49 
 50     public void setGender(String gender) {
 51         this.gender = gender;
 52     }
 53 
 54     public Integer getAge() {
 55         return age;
 56     }
 57 
 58     public void setAge(Integer age) {
 59         this.age = age;
 60     }
 61 
 62     public String getAddress() {
 63         return address;
 64     }
 65 
 66     public void setAddress(String address) {
 67         this.address = address;
 68     }
 69 
 70     public String getQq() {
 71         return qq;
 72     }
 73 
 74     public void setQq(String qq) {
 75         this.qq = qq;
 76     }
 77 
 78     public String getEmail() {
 79         return email;
 80     }
 81 
 82     public void setEmail(String email) {
 83 
 84         this.email = email;
 85     }
 86 
 87     public String getUsername() {
 88         return username;
 89     }
 90 
 91     public void setUsername(String username) {
 92         this.username = username;
 93     }
 94 
 95     public String getPassword() {
 96         return password;
 97     }
 98 
 99     public void setPassword(String password) {
100         this.password = password;
101     }
102 }
User
 1 package cn.itcast.domain;
 2 
 3 import java.util.List;
 4 
 5 public class PageBean {
 6     //总页数
 7     private int totalPage;
 8     //总条数
 9     private int totalCount;
10     //页大小
11     private int pageSize;
12     //当前页
13     private int currentPage;
14     //页数据
15     private List pageData;
16 
17     public PageBean() {
18     }
19 
20     public int getTotalPage() {
21         return totalPage;
22     }
23 
24     public void setTotalPage(int totalPage) {
25         this.totalPage = totalPage;
26     }
27 
28     public int getTotalCount() {
29         return totalCount;
30     }
31 
32     public void setTotalCount(int totalCount) {
33         this.totalCount = totalCount;
34     }
35 
36     public int getPageSize() {
37         return pageSize;
38     }
39 
40     public void setPageSize(int pageSize) {
41         this.pageSize = pageSize;
42     }
43 
44     public int getCurrentPage() {
45         return currentPage;
46     }
47 
48     public void setCurrentPage(int currentPage) {
49         this.currentPage = currentPage;
50     }
51 
52     public List getPageData() {
53         return pageData;
54     }
55 
56     public void setPageData(List pageData) {
57         this.pageData = pageData;
58     }
59 }
PageBean

黑马第1个案例 登录验证 增删改查 条件查询+分页_第1张图片

转载于:https://www.cnblogs.com/mozq/p/10859597.html

你可能感兴趣的:(黑马第1个案例 登录验证 增删改查 条件查询+分页)