温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

cookie实例运用分析

发布时间:2022-03-15 15:13:18 来源:亿速云 阅读:142 作者:iii 栏目:web开发

这篇“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实例运用分析”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI