zoukankan      html  css  js  c++  java
  • 会话 Cookie 和Session

    1.Cookie  第一次发送请求显示"还没有数据...."

    public class CookieDemo extends HttpServlet {
        
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //创建cookie 对象
            Cookie cookie = new Cookie("name", "ckang");
            Cookie cookie1 = new Cookie("email","ckang@163.com");
            // 发送cookie到浏览器
            response.addCookie(cookie);
            response.addCookie(cookie1);
            
            //获取从浏览器中请求中带来的cookie信息
            Cookie[] cookies = request.getCookies();
            if (null != cookies) {
                for(Cookie c : cookies){
                    String name = c.getName();
                    String value = c.getValue();
                    System.out.println(name+":::"+value);
                }
            }else{
                System.out.println("cookie还没有数据...");
            }
        }
    }

    效果图:

     1.3 案例:

    public class HistoryAppearServlet extends HttpServlet {
    	@Override
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		response.setContentType("text/html;charset=utf-8");//不写浏览器乱码
    		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		String curTime = format.format(new Date());
    		
    		Cookie[] cookies = request.getCookies();
    		String lastTime = null;
    		if (cookies != null) {
    			for(Cookie c : cookies){
    				if(c.getName().equalsIgnoreCase("lastTime")){//第n次
    					lastTime = c.getValue();//上次访问的时间
    					response.getWriter().write("欢迎回来,您上次访问的时间是"+lastTime+",当前时间是"+curTime);
    					//更新cookie最新时间,并且发送给浏览器保存...
    					c.setValue(curTime);
    					c.setMaxAge(1*24*30*60*60);
    					response.addCookie(c);
    					break;
    				}
    			}
    		}
    		
    		if(cookies == null || lastTime==null){//第一次
    			response.getWriter().write("欢迎光临,当前时间为"+curTime);
    			//保存到cookie并且发送给浏览器
    			Cookie c = new Cookie("lastTime",curTime);
    			c.setMaxAge(1*30*24*60*60);//保存到硬盘一个月时间
    			response.addCookie(c);
    		}
    	}
    }
    

      

    2.Session

  • 相关阅读:
    在蓝鲸标准运维上进行原子开发二
    python 使用eval报错NameError: name ‘null’ is not defined
    前端时间转换 2019-08-18T16:00:00.000Z 转换成格式2019-08-18
    python list排序
    Django 分页Paginator的简单用法
    蓝鲸ESB自定义组件的部署步骤
    Unity对象池的实现
    Unity3D UGUI实现Toast
    C#中扩展方法的使用
    Unity3D实现多语言切换
  • 原文地址:https://www.cnblogs.com/bravolove/p/5883195.html
Copyright © 2011-2022 走看看