叨叨两句

  1. ~

Filter

自动登录

  1. 登录页面填写信息,提交后跳转至loginServlet
  2. 调用service方法处理登录业务
  3. 判断返回是否为空,若不为空,则说明登录成功
  4. 如果登录成功,判断是否需要自动登录
  5. 如果需要就将用户名和密码存储到cookie中,并通过response发送客户端
  6. filter到cookie中获取用户名和密码
  7. 调用service的方法,根据用户名和密码查询user对象
  8. 将user对象存储到session中
  9. 放行
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.获得用户名和密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            //2.调用业务,进行登录
            LoginService loginService = new LoginService();
            User user = loginService.login(username,password);
            
            //3.判断用户是否为空
            if(user != null){
                //登录成功
                //response.getWriter().print("Login Success...");
                String auto = request.getParameter("auto");
                
                if(auto != null && "ok".equalsIgnoreCase(auto)){
                    System.out.println("用户勾选了自动登录...");
                    Cookie cookie = new Cookie("autoLogin", username+"-"+password);
                    cookie.setPath(request.getContextPath());
                    cookie.setMaxAge(60*60*24);
                    response.addCookie(cookie);    
                }
                
            
                
                request.getSession().setAttribute("user", user);
                response.sendRedirect(request.getContextPath()+"/WEB01/index.jsp");
            }else{
                //登录失败
                response.getWriter().print("Login Fail...");
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
            //登录失败
            response.getWriter().print("Login Fail...");
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

Wall_Breaker
2.1k 声望1.2k 粉丝

生死之间,就是我的跃迁之路,全程记录,欢迎见证