cookie实现保持用户登陆状态

package com.chen.controllers;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.var.Model;

import org.springframework.beans.factory.annotation.Autowired;

import com.chen.bean.User;
import com.chen.service.UserService;
import com.chen.utils.CookieUtils;
import com.chen.utils.MD5Utils;

public class LoginInterceptor extends ControllerInterceptorAdapter {

    @Autowired
    private UserService us;

    public LoginInterceptor() {
        setPriority(29000);
    }

    @Override
    protected Object before(Invocation inv) throws Exception {
        String url = inv.getRequest().getRequestURL().toString();
        // 登陆、访问首页,退出账户操作放行
        boolean isLogin = url.contains("/login");
        boolean isIndex = url.contains("/index");
        boolean isLogout = url.contains("/logout");
        boolean isRegister = url.contains("/register")
        if (isLogin || isIndex || isLogout || isRegister) {
            return null;
        }
        // 校验登陆,使用cookie
        Model model = inv.getModel();
        String cookieValue = null;
        Cookie[] cookies = inv.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (CookieUtils.cookieDomainnName.equals(cookie.getName())) {
                    // 找到用户cookie
                    cookieValue = cookie.getValue();
                    break;
                }
            }
            // 如果cookie值为空,登陆页面
            if (cookieValue == null) {
                model.add("info", "登陆超时,请重新登陆");
                return "login";
            }
            // cookie值不为空,对cookie进行base64解码
            String cookieValueNoBase64 = new String(
                    com.sun.org.apache.xerces.internal.impl.dv.util.Base64
                            .decode(cookieValue));
            // 对cookie进行分离
            String cookieSpilt[] = cookieValueNoBase64.split(":");
            // 飞法访问网站
            if (cookieSpilt.length != 3) {
                model.add("info", "非法访问本网站,请重新登陆");
                return "login";
            }
            // 验证cookie有效期
            Long viladTime = new Long(cookieSpilt[1]);
            if (System.currentTimeMillis() > viladTime) {
                System.out.println(System.currentTimeMillis());
                System.out.println(viladTime);
                // 超过有效期,删除cookie,然后重新登陆
                CookieUtils.cleanCookie(inv.getResponse());
                inv.getModel().add("info", "登陆超时,请重新登陆");
                return "login";
            }
            // 验证数据库中有这个用户,并合成cookie的加密串与客户端的cookie加密串对比
            String userName = cookieSpilt[0];
            User user = us.getUser(userName, null);
            if (user != null) {
                // 查找到user,合成cookie型加密串
                String userCookieStr = MD5Utils.md5(user.getName() + viladTime
                        + CookieUtils.webKey);
                if (userCookieStr.equals(cookieSpilt[2])) {
                    return null;
                }
                model.add("info", "状态异常,请重新登陆");
            }
        } 
        // cookie不存在,跳转到登陆页面
        return "login";
        }
    }
package com.chen.controllers;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.var.Model;

import org.springframework.beans.factory.annotation.Autowired;

import com.chen.bean.User;
import com.chen.service.UserService;
import com.chen.utils.CookieUtils;
import com.chen.utils.MD5Utils;

public class LoginInterceptor extends ControllerInterceptorAdapter {

    @Autowired
    private UserService us;

    public LoginInterceptor() {
        setPriority(29000);
    }

    @Override
    protected Object before(Invocation inv) throws Exception {
        String url = inv.getRequest().getRequestURL().toString();
        // 登陆、访问首页,退出账户操作放行
        boolean isLogin = url.contains("/login");
        boolean isIndex = url.contains("/index");
        boolean isLogout = url.contains("/logout");
        if (isLogin || isIndex || isLogout) {
            return null;
        }
        // 校验登陆,使用cookie
        Model model = inv.getModel();
        String cookieValue = null;
        Cookie[] cookies = inv.getRequest().getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (CookieUtils.cookieDomainnName.equals(cookie.getName())) {
                    // 找到用户cookie
                    cookieValue = cookie.getValue();
                    break;
                }
            }
            // 如果cookie值为空,登陆页面
            if (cookieValue == null) {
                model.add("info", "登陆超时,请重新登陆");
                return "login";
            }
            // cookie值不为空,对cookie进行base64解码
            String cookieValueNoBase64 = new String(
                    com.sun.org.apache.xerces.internal.impl.dv.util.Base64
                            .decode(cookieValue));
            // 对cookie进行分离
            String cookieSpilt[] = cookieValueNoBase64.split(":");
            // 飞法访问网站
            if (cookieSpilt.length != 3) {
                model.add("info", "非法访问本网站,请重新登陆");
                return "login";
            }
            // 验证cookie有效期
            Long viladTime = new Long(cookieSpilt[1]);
            if (System.currentTimeMillis() > viladTime) {
                System.out.println(System.currentTimeMillis());
                System.out.println(viladTime);
                // 超过有效期,删除cookie,然后重新登陆
                CookieUtils.cleanCookie(inv.getResponse());
                inv.getModel().add("info", "登陆超时,请重新登陆");
                return "login";
            }
            // 验证数据库中有这个用户,并合成cookie的加密串与客户端的cookie加密串对比
            String userName = cookieSpilt[0];
            User user = us.getUser(userName, null);
            if (user != null) {
                // 查找到user,合成cookie型加密串
                String userCookieStr = MD5Utils.md5(user.getName() + viladTime
                        + CookieUtils.webKey);
                if (userCookieStr.equals(cookieSpilt[2])) {
                    return null;
                }
                model.add("info", "状态异常,请重新登陆");
            }
        } 
        // cookie不存在,跳转到登陆页面
        return "login";
        }
    }
package com.chen.utils;

import java.security.NoSuchAlgorithmException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import net.paoding.rose.web.Invocation;

public class CookieUtils {

    //cookie最大生存时间
    private static final int cookieMageAge = 30*60;//半小时

    //cookieName
    public static final String cookieDomainnName = "com.yeepay";

    //加密cookie时网站自定码
    public static final String webKey = "yeepay";

    //保持cookie
    public static void saveCookie(String userName,Invocation inv) throws NoSuchAlgorithmException {
        //cookie有效时间  
        long validTime = System.currentTimeMillis()+cookieMageAge*1000;

        //md5加密id+validTiem+webkey
        String md5cookieStr = MD5Utils.md5(userName+validTime+webKey);

        //合成保存的完整cookie串:id+validtime+mdcookieStr
        String cookieValue = userName+":"+validTime+":"+md5cookieStr;

        //base64合成保存cookie保持在本地
        String saveCookie = new String(Base64.encode(cookieValue.getBytes()));

        Cookie userCookie =  new Cookie(cookieDomainnName, saveCookie);

        //cookie的生存时间,应该大于有效时间viladTime
        userCookie.setMaxAge(3600*24);
        userCookie.setPath("/roselogin/");

        //写到客户端
        inv.getResponse().addCookie(userCookie);
    }

    //s删除cookie
    public static void cleanCookie(HttpServletResponse respose) {
        Cookie cookie = new Cookie(cookieDomainnName, null);
        cookie.setMaxAge(0);
        cookie.setPath("/roselogin/");
        respose.addCookie(cookie);
    }
}

你可能感兴趣的:(cookie)