【300天】每日項目總結系列038(2017.12.02)

叨叨兩句

  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);
    }

}
相關文章
相關標籤/搜索