JavaはCookieまたはSessionを利用してログイン検証を実現

5231 ワード

簡単なログイン検証は、SessionまたはCookieによって実現できます.具体的には、次のとおりです.
一、Sessionによるログイン検証
1、カスタムHandlerInterceptor
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object obj, Exception err)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object obj, ModelAndView mav) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object obj) throws Exception {
        //  session       
        String str = (String) request.getSession().getAttribute("isLogin");
        //            true,  true      controller   
        if(str!=null){
            return true;
        }
        //                 ,   false,     controller   
        response.sendRedirect("/loginPage");
        return false;
    }
}

2、Controllerを作成し、ログインを実現する
@Controller
@RequestMapping("")
public class BackendController {

    
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public String login(HttpServletRequest request,RedirectAttributes model, String name, String password){
        //      ,       session    ,       
        if ("xxx".equals(name)&&"123456".equals(password)){
            request.getSession().setAttribute("isLogin","yes");
            return "redirect:IndexPage";
        }else {
            //            ,     ,           RedirectAttributes
            model.addFlashAttribute("error","    ");
            return "redirect:loginPage";
        }
    }
    //  ,              
    @RequestMapping(value = "/loginOut", method = {RequestMethod.GET})
    public String loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute("isLogin");
        return "redirect:loginPage";
    }
   

}

2、Cookieによるログイン検証
         ログインステータスがブラウザを終了してもしばらく保持したい場合は、セッションをCookieに変更できます.
 1、カスタムHandlerInterceptor
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object obj, Exception err)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object obj, ModelAndView mav) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object obj) throws Exception {
//          request cookie
        Cookie[] cookies = request.getCookies();
        if (null==cookies) {
            System.out.println("  cookie==============");
        } else {
//              cookie           true    controller   
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("isLogin")){
                    return true;
                }
            }
        }
//                        ,  false,     controller   
        response.sendRedirect("/loginPage");
        return false;
    }
}

2、Controller層コードを作成してログインを実現する
@Controller
@RequestMapping("")
public class BackendController {

    @RequestMapping(value = "/loginPage", method = {RequestMethod.GET})
    public String loginPage(HttpServletRequest request, String account, String password) {
        return "login";
    }

    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public String login(HttpServletRequest request, HttpServletResponse response, RedirectAttributes model, String name, String password) {
        if ("xxx".equals(name) && "123456".equals(password)) {
            Cookie cookie = new Cookie("isLogin", "yes");
            cookie.setMaxAge(30 * 60);//    30min
            cookie.setPath("/");
            response.addCookie(cookie);
            return "redirect:IndexPage";
        } else {
            model.addFlashAttribute("error", "    ");
            return "redirect:loginPage";
        }
    }

    @RequestMapping(value = "/logOut", method = {RequestMethod.GET})
    public String loginOut(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("isLogin")) {
                cookie.setValue(null);
                cookie.setMaxAge(0);//     cookie
                cookie.setPath("/");
                response.addCookie(cookie);
                break;
            }
        }
        return "redirect:loginPage";
    }
}

また,SessionベースでもCookieベースでもログイン検証にはHandlerInteceptorを構成し,URLに対するブロックフィルタリング機構を追加する必要がある.