UserServlet主要用于用户登录,退出以及密码修改方面的事务。鉴于对网络应用的安全性考虑,
所以user将被写在session里面,用以在某些管理页面达到认证作用。
1 private void login(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3 String userName = request.getParameter("username");
4 String password = request.getParameter("password");
5 String sql = "select id,username,password from users where username = ? and password = ?";
6 String params[] = {userName, password};
7 List users = null;
8
9 QueryRunner qr = DbHelper.getQueryRunner();
10 try {
11 users = (List) qr.query(sql, new BeanListHandler(User.class), params);
12 } catch (SQLException ex) {
13 Logger.getLogger(UserServlet.class.getName()).log(Level.SEVERE, null, ex);
14 }
15 if (users.size()!=0) {
16 User user = (User) users.get(0);
17 HttpSession session = request.getSession();
18 session.setAttribute("user", user);
19 response.sendRedirect(request.getContextPath()+"/BlogServlet?method=list");
20 } else {
21 request.setAttribute("message", "错误的用户名或密码");
22 request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
23 }
24 }
logout相对很简单,使session失效即可
1 private void logout(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3 HttpSession session = request.getSession();
4 session.invalidate();
5 response.sendRedirect(request.getContextPath());
6 }
modifyPassword
1 private void modify(HttpServletRequest request, HttpServletResponse response)
2 throws ServletException, IOException {
3 String oldPassword = request.getParameter("oldPassword");
4 String newPassword = request.getParameter("newPassword");
5 String confirmPassword = request.getParameter("confirmPassword");
6
7 HttpSession session = request.getSession();
8 User user = (User) session.getAttribute("user");
9 if (!user.getPassword().equals(oldPassword)) {
10 request.setAttribute("message", "与原密码不匹配");
11 } else {
12 if (!newPassword.equals(confirmPassword)) {
13 request.setAttribute("message", "新密码与确认密码不匹配");
14 } else {
15 String sql = "update users set password =? where id = "+ user.getId();
16 QueryRunner qr = DbHelper.getQueryRunner();
17 try {
18 qr.update(sql, newPassword);
19 } catch (SQLException ex) {
20 Logger.getLogger(UserServlet.class.getName()).log(Level.SEVERE, null, ex);
21 }
22 request.setAttribute("message", "密码修改成功");
23 }
24 }
25 request.getRequestDispatcher("/admin/modifyPassword.jsp").forward(request, response);
26 }