cookie实现记录访问

注意:1.设置的时间字符串特殊字符如空格在添加到cookie前要进行URL编码,获取打印前要进行解码。

   2.req获取的cookie是客户端带过来的,respond回去的是更改后的,要把客户端带来的和相应回去的cookie区分开。

 

 

/**
 * cookie显示上次访问时间
 */
@WebServlet("/ServletCookie")
public class ServletCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        boolean flag=false;
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){

            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                String value = cookie.getValue();
                if(name.equals("lastTime")){
                    flag=true;
                    //给客户端响应一个新的cookie
                    String encode = getString();
                    cookie.setValue(encode);
                    //相应时间的cookie给客户端
                    cookie.setMaxAge(60*60*24*30);
                    response.addCookie(cookie);
                    //这个是请求带来的cookie
                    //解码前
                    System.out.println(value);
                    String decode = URLDecoder.decode(value,"utf-8");
                    response.getWriter().write("<h1>上次的访问时间为"+decode+"</h1>");
                    //访问到其中一个退出
                    break;
                }
            }
        }

        if (cookies==null&&cookies.length==0&&flag==false){
            String encode = getString();
            Cookie cookie=new Cookie("lastTime",encode);
            response.getWriter().write("欢迎首次访问!");
            //相应时间的cookie给客户端
            cookie.setMaxAge(60*60*24*30);

            response.addCookie(cookie);
        }

    }

    private String getString() throws UnsupportedEncodingException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月-dd日 HH:mm:ss");
        String format = sdf.format(date);
        System.out.println("编码前"+format);
        String encode = URLEncoder.encode(format, "utf-8");
        System.out.println("编码后"+encode);
        return encode;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

 

posted @ 2019-05-20 01:55  findlisa  阅读(479)  评论(0编辑  收藏  举报