使用cookie实现自动登录

一、从登录——>主页面,进行的过程是,输入 用户名和密码,以及验证码,点击“登录”跳转到Activity.jsp

login1.action(跳转到登录页面)

/** 跳转到login(有积分排行榜) */
    @RequestMapping("/login1.action")
    public String login() {
        return "login";
    }

login.action(从登录页面跳转到主页面)

/** 登录 */
    @RequestMapping("/login.action")
    public String login(String nickName, String password, String authCode,
            String autoLogin, HttpSession session, Model model,
            HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("autoLogin:" + autoLogin);//自动登录多选框状态,未选中时为null,选中时为on
        // 登录积分和等级
        PointAction loginPoint = null;
        Graderecord loginLevel = null;
        if (authCode == null || authCode == "") {
            model.addAttribute("msg", "请填写验证码!");
            return "login";
        }
        if (!authCode.equals(session.getAttribute("authCode"))) {
            model.addAttribute("msg", "验证码错误");
            return "login";
        }
        try {
            // 根据页面用户名查询用户信息
            Memberinfo memberinfo = memberservice.loginMemberInfo(nickName);
            session.setAttribute("nickName", nickName);
            // 判断密码是否正确
            if (password.equals(memberinfo.getPassword())) {
                memberservice.loginAction(memberinfo, loginPoint, session,
                        loginLevel);
                if (autoLogin != null) {
                    // 保存cookie
                    try {
                        Cookie usernameCookie = new Cookie("nickname",
                                URLEncoder.encode(nickName, "utf-8"));
                        Cookie passwordCookie = new Cookie("password", password);
                        usernameCookie.setMaxAge(360 * 24 * 60);// 设置一年有效期
                        passwordCookie.setMaxAge(360 * 24 * 60);
                        usernameCookie.setPath("/");// 可在同一应用服务器内共享方法
                        passwordCookie.setPath("/");
                        resp.addCookie(usernameCookie);
                        resp.addCookie(passwordCookie);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                return "activity";
            } else {
                model.addAttribute("msg", "请输入正确密码");
            }
            return "login";
        } catch (MemberServiceException e) {
            e.printStackTrace();
            model.addAttribute("msg", e.getMessage());
            return "login";
        }
    }

在此时,进行Cookie的保存,即中间的这一段代码

if (autoLogin != null) {//判断自动登录多选框的状态,若选中则进行Cookie的保存
                    // 保存cookie
                    try {
                        Cookie usernameCookie = new Cookie("nickname",
                                URLEncoder.encode(nickName, "utf-8"));
                        Cookie passwordCookie = new Cookie("password", password);
                        usernameCookie.setMaxAge(360 * 24 * 60);// 设置一年有效期
                        passwordCookie.setMaxAge(360 * 24 * 60);
                        usernameCookie.setPath("/");// 可在同一应用服务器内共享方法
                        passwordCookie.setPath("/");
                        resp.addCookie(usernameCookie);
                        resp.addCookie(passwordCookie);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                return "activity";

在index.jsp页面中调用checkAutoLoginAction.action

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="refresh" content="0;url='checkAutoLoginAction.action'">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
  </body>
</html>

checkAutoLoginAction.action(取出Cookie

// ------自动登录----------------------------------------------------------------------------------------------------------------------------
    @RequestMapping("checkAutoLoginAction.action")
    public String checkAutoLoginAction(HttpServletRequest req,
            HttpServletResponse resp, HttpSession session) throws Exception {
        Cookie[] cookies = req.getCookies();
        System.out.println("cookie是否为空:" + cookies);
        String nickname = "";
        String password = "";
        if (cookies != null) {//判断Cookie是否为空
            for (Cookie c : cookies) {
                if ("nickname".equals(c.getName())) {
                    nickname = URLDecoder.decode(c.getValue(), "utf-8");
                }
                if ("password".equals(c.getName())) {
                    password = URLDecoder.decode(c.getValue(), "utf-8");
                }
            }
            Memberinfo m = memberservice.login(nickname, password);
            session.setAttribute("nickName", m.getNickName());
            System.out.println("m是否为空:" + m);
            if (m != null) {//如果根据Cookie中的用户名和密码查询出的用户信息存在且正确,再进行一系列的更新跳转工作
                Calendar c = Calendar.getInstance();
                c.setTime(m.getLatestDate());
                String date = new SimpleDateFormat("EEEE").format(c.getTime());
                return "activity";
            }
        }
        req.setAttribute("msg", "账户密码失效,请重新登录");
        return "forward:/login1.action";
    }

三、操作

第一步,输入http://localhost:8888/ssh/login1.action,跳转到登录页面

第二步,输入nickName和password,勾选“自动登录”,点击“登录”,跳转到Activity.jsp主页面

第三步,若成功登录到主页面,则注销

第四步,输入http://localhost:8888/ssh/index,即可使用checkAutoLoginAction.action,直接跳转到主页面,省略了第二步

原文地址:https://www.cnblogs.com/xiufengchen/p/10404575.html