2012軟考軟件設(shè)計師輔導(dǎo):如何設(shè)置以及刪除cookie

字號:

-
    /**
    * 刪除cookie
    */
    public static void clearCookie(HttpServletRequest request,HttpServletResponse response, String path) {
    Cookie[] cookies = request.getCookies();
    try{
    for(int i=0;i《cookies.length;i++) {
    //System.out.println(cookies[i].getName() + “:” + cookies[i].getValue());
    Cookie cookie = new Cookie(cookies[i].getName(), null);
    cookie.setMaxAge(0);
    cookie.setPath(path);//根據(jù)你創(chuàng)建cookie的路徑進(jìn)行填寫
    response.addCookie(cookie);
    }
    }catch(Exception ex) {
    System.out.println(“刪除Cookies發(fā)生異常!”);
    }
    }
    public static void setCookie(HttpServletResponse response, String name, String value, String path) {
    if (logger.isDebugEnabled()) {
    logger.debug(“Setting cookie ‘” + name + “' on path ’” + path + “‘”);
    }
    Cookie cookie = new Cookie(name, value);
    cookie.setSecure(false);
    cookie.setPath(path);
    cookie.setMaxAge(Constants.COOKIE_INVALID_TIME);
    response.addCookie(cookie);
    // logger.info(“setCookie 完成……”);
    }
    //調(diào)用
    String cookiename = “vbo”;
    String cookievalue = “cb”;
    String path = “/”;
    setCookie(response, cookiename , cookievalue , path);
    clearCookie(request,response,path);//如果有name的話,方法也要增加name過去才能匹配