java Cookie 获取历史记录列表_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java Cookie 获取历史记录列表

java Cookie 获取历史记录列表

 2016/9/2 5:36:23  linshihao  程序员俱乐部  我要评论(0)
  • 摘要:/***获取Cookie里面的东西*/protectedList<String>getCookieList(){Cookie[]cookies=null;Cookiecookie=null;StringcookieValue=null;StringcookieName=null;cookies=request.getCookies();if(cookies==null){returnnull;}List<String>cookieList=newArrayList<
  • 标签:Java Cookie
class="java" name="code">/**
     * 获取Cookie里面的东西
     */
    protected List<String> getCookieList() {
        Cookie[] cookies = null;
        Cookie cookie = null;
        String cookieValue = null;
        String cookieName = null;
        cookies = request.getCookies();
        if(cookies==null){
            return null;
        }

        List<String> cookieList = new ArrayList<String>();
        for (int i = cookies.length - 1; i >= 0; i--) {
            cookie = cookies[i];
            try {
                cookieValue = URLDecoder.decode(cookie.getValue(),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            cookieName = cookie.getName();
            int cookieNameIndex = 0;
            cookieNameIndex = cookieName.indexOf("search");
            if (cookieNameIndex != -1 && cookieValue!= null && StringUtils.isNotBlank(cookieValue)) {
                cookieList.add(cookieValue);
            }
        }
        //去重
        removeDuplicate(cookieList);
        //取记录
        List<String> searchList = new ArrayList<String>();
        int index = 0;
        for(int i=0;i< cookieList.size(); i++){
            if(index< Constants.COOKIES_NUM){
                searchList.add(cookieList.get(i));
            }
            index++;
        }
        return searchList;
    }
    //去重
    private static void removeDuplicate(List list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    list.remove(j);
                }
            }
        }
    }
//设置
    protected void setCookie(String keyWord){
        try {
            //关键点
            keyWord = URLEncoder.encode(keyWord,"UTF-8");
        } catch (UnsupportedEncodingException e) { }
        Cookie cookie = new Cookie("search"+new Date().getTime(), keyWord);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 24 * 365 * 1);
        response.addCookie(cookie);
    }
//删除
    protected void removeCookie(){
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie:cookies){
            cookie.setMaxAge(0);
        }
    }


如果cookie 考虑前端被禁掉的话可以考虑参考这段代码
发表评论
用户名: 匿名