2018-03-04 Filter類(四):實現(xiàn)用戶自動登錄 --- cookie

筆記如下
  • web.xml


    4.png
  • 用戶登錄


    4.png
  • 自動登錄過濾器

//自動登錄過濾器
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // TODO Auto-generated method stub
        
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp= (HttpServletResponse) response;
        
        //判斷是否已經(jīng)登錄
        //如果登錄,信息存在session中
        if( req.getSession().getAttribute("loginUser") != null ){
            
            //說明已經(jīng)登錄,直接放行
            chain.doFilter(req, resp);
        
        }else{
            //說明沒有登錄
            
            //找目標(biāo)cookie
            Cookie[] cookies = req.getCookies();
            
            Cookie targetCookie = findTargetCookie(cookies,"autologn");
            
            
            if (targetCookie == null) {
                //沒找到目標(biāo)cookei
                
                chain.doFilter(req, resp);
                
                
            }else{
                //找到了,
                
                
                String username = targetCookie.getValue().split("#")[0];
                String password = targetCookie.getValue().split("#")[1];
                
                //去登陸,去數(shù)據(jù)庫查找用戶信息
                UserService us =new UserService();
                User loginUser = us.loginByUsernameAndPassword(username,password);
                
                if (loginUser == null) {
                    //說明用戶名和密碼被篡改了
                    //放行
                    chain.doFilter(req, resp);
                }else{
                    //將user存到session中去
                    req.getSession().setAttribute("loginUser", loginUser);
                    chain.doFilter(req, resp);
                }
                
            }
            
            
        }
                
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。