cookie的使用

1. 添加cookie

public static boolean addCookie(String str, HttpServletResponse response) {
        String name = null;
        try {
            name = URLEncoder.encode(str, "utf-8"); // 转码,解决中文保存的问题
        } catch (Exception e) {
            e.printStackTrace();
        }
        Cookie cookie = new Cookie("user", name);
        cookie.setMaxAge(60 * 60 * 24 * 14);// cookie保存两周
        response.addCookie(cookie);
        System.out.println("添加cookie成功");
        return true;
    }

 

2. 取得cookie

public static String getCookie(HttpServletRequest request) {
        String name;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println("cookie: " + cookie.getName());
                if ("user".equals(cookie.getName())) {
                    name = cookie.getValue();
                    return name;
                }
            }
        }
        return null;
    }

 

posted @ 2012-07-12 23:53  垚淼  阅读(333)  评论(0编辑  收藏  举报