欢迎光临
我们一直在努力

cookie实例运用分析

这篇“cookie实例运用分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“cookie实例运用分析”文章吧。

cookie学习

/**
 在服务器中的Servlet判断是否有一个名为lastTime的cookie
 1. 有:不是第一次访问
 1. 响应数据:欢迎回来,您上次访问时间为:2018年6月10日11:50:20
 2. 写回Cookie:lastTime=2018年6月10日11:50:01
 2. 没有:是第一次访问
 1. 响应数据:您好,欢迎您首次访问
 2. 写回Cookie:lastTime=2018年6月10日11:50:01

了解一下
URLEncoder编码和URLDecoder解码,都需要使用一个变量来接收
 */

@WebServlet("/cookieDemo")
public class CookieDemo 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();
                
                if ("lastTime".equals(name)){
                    //再次光临
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    str_date=URLEncoder.encode(str_date,"utf-8");

                    flag=true;
                    String value = cookie.getValue();
                    value =URLDecoder.decode(value,"utf-8");
                    response.getWriter().write("<h2>再次光临,你上次登录的时间是:"+value+"</h2>");
                    
                    cookie.setValue(str_date);
                    cookie.setMaxAge(60*60*24*30);
                    response.addCookie(cookie);
                    break;
                }
            }
        }

        if(cookies==null||cookies.length==0||flag==false){
            //第一次
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            System.out.println("编码前:" + str_date);
            str_date =URLEncoder.encode(str_date,"utf-8");
            System.out.println("编码后:" + str_date);

            Cookie cookie = new Cookie("lastTime",str_date);
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            str_date =URLDecoder.decode(str_date,"utf-8");
            response.getWriter().write("<h2>你好,欢迎首次登录  :  "+str_date+"</h2>");
        }
    }

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

以上就是关于“cookie实例运用分析”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注云搜网行业资讯频道。

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。