java cookie 工具类代码以及使用

java cookie 工具类代码以及使用

一.导入依赖

    <!--cookie-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <!-- 这个scope 只能作用在编译和测试时,同时没有传递性。表示在运行的时候不添加此jar文件 -->
      <scope>provided</scope>
    </dependency>

二.定义cookie操作工具类

package cn.ydsat.aisell.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//cookie缓存类
public class CookieUtil {

    private static String PATH = "/";

    public static void createCookie(String username,String password,Integer liveTime,HttpServletResponse response){
        //根据前台传递过来的正确数据设置cookie
        Cookie nameCookie = new Cookie("username", username);
        //设置Cookie的有效期
        nameCookie.setMaxAge(60 * 60 * 24 * liveTime);
        nameCookie.setPath(PATH);
        //密码
        Cookie pwdCookie = new Cookie("password", password);
        //设置Cookie的有效期
        pwdCookie.setMaxAge(60 * 60 * 24 * liveTime);
        pwdCookie.setPath(PATH);
        //添加cookie到浏览器
        response.addCookie(nameCookie);
        response.addCookie(pwdCookie);
    }

    /**
     * 清除所有cookie
     */
    public static void clearAll(HttpServletRequest req,HttpServletResponse resp){
        Cookie[] cookies = req.getCookies(); //获取浏览器中的所有cookie
        for (Cookie cookie:cookies){
            cookie.setMaxAge(0);  //设置存活时间为o
            cookie.setPath(PATH);
            resp.addCookie(cookie);
        }
    }
    /**
     * 清除单个cookie
     */
    public static void clear(String name,HttpServletRequest req,HttpServletResponse resp){

        Cookie newCookie=new Cookie("username",null); //假如要删除名称为username的Cookie

        newCookie.setMaxAge(0); //立即删除型

        newCookie.setPath(PATH); //项目所有目录均有效,这句很关键,否则不敢保证删除

        resp.addCookie(newCookie); //重新写入,将覆盖之前的
    }
}

三.使用

根据自己的需求调用CookieUtil中的方法

(1)可将登陆信息存放到cookie 下次直接使用cookie自动登陆,这里是使用了shiro安全框架进行认证,将认证后的信息存入cookie中(shiro 1 中有涉及相关shiro的使用以及配置)

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult login(String username, String password,Model model, HttpServletResponse resp){
        /*String code2 = (String)req.getSession().getAttribute("code");*/
        System.out.println(username);
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            if(!subject.isAuthenticated()){//判断当前用户是否登录 布尔值  取反
                subject.login(token);//认证登陆
            }
            //将登陆的用户信息存入域对象之中
            Employee employee = ((Employee) subject.getPrincipal());//获取当前用户
            UserContext.setSession(employee);
            //创建2天的cookie
            CookieUtil.createCookie(username,password,2,resp);
            return new AjaxResult();

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new AjaxResult(false, "账号不存在!!");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return new AjaxResult(false, "密码错误!!");
        }catch (AuthenticationException e){
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return new AjaxResult(false, "您的错误史无前例!速速检查");
    }

(2) 使用Cookie登陆

    /**
     * 跳转到登录界面
     * @return
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(Model model, HttpServletRequest req, HttpServletResponse response){
        //浏览器中获取cookie列表
        Cookie[] cookies = req.getCookies();
        String cookie_username = null;
        String cookie_password = null;
        //如果存在cookie
        if(cookies!=null){
            try {
                //遍历cookie列表 获取username 以及password信息
                for(Cookie cookie : cookies){
                    //获得名字是cookie_username和cookie_password
                    if("username".equals(cookie.getName())){
                        cookie_username = cookie.getValue();
                    }
                    if("password".equals(cookie.getName())){
                        cookie_password = cookie.getValue();
                    }
                }
                //如果cookie中有满足登陆的账户名以及密码,那么就自动登录
                if (cookie_username!=null && cookie_password!=null){
                    //调用cookie进行shiro安全认证进行登录
                    cookieLogin(cookie_username,cookie_password);
                    //从定向到首页
                    return "redirect:/main";
                }
            }catch (UnknownAccountException e) {
                return "login";
            } catch (IncorrectCredentialsException e) {
                return "login";
            } catch (Exception e) {
                e.printStackTrace();
                return "login";
            }
        }

        return "login";
    }

(3)使用Cookie登陆系统

    /**
     * Cookie认证
     */
    public AjaxResult cookieLogin(String username, String password) {
        //获取用户
        Subject subject = SecurityUtils.getSubject();
        //如果没有认证成功,则进行认证
        if (!subject.isAuthenticated()) {
            //把用户名和密码封装成一个token对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //进行认证
            subject.login(token);
            //获取用户
            Employee employee = (Employee) subject.getPrincipal();
            //将用户放入Session
            UserContext.setSession(employee);
        }
        return new AjaxResult();
    }

(3)在使用shiro自带的注销认证方法时,也要清空cookie中的数据

    /*注销登陆
    * */
    @RequestMapping("/cookieclear")
    public String logout(HttpServletRequest request,HttpServletResponse response) {
        //清除浏览其中已有cookie
        CookieUtil.clearAll(request,response);
        /*要从定向得到shiro的注销方法去*/
        return "redirect:/logout";
    }

cookie的基本使用就是这样,但是Cookie并不是很安全的,考虑到极大的安全性方面,或者做更为严谨的项目可以使用Session。

发布了31 篇原创文章 · 获赞 23 · 访问量 3812

猜你喜欢

转载自blog.csdn.net/leilei1366615/article/details/98952872