• 会话 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

  • 相关阅读:
    How to Setup a Private Proxy Server on EC2 in Under 10 Minutes
    How to Create a Cron Job (Scheduled Task) for Your Website or Blog
    NPM, BOWER, GIT, AND BASH PROXY CONFIGURATIONS
    Android: 通过Runtime.getRuntime().exec调用底层Linux下的程序或脚本
    Proguard breaking audio file in assets or raw
    SOCKSify Ruby
    UNIX / Linux: 2 Ways to Add Swap Space Using dd, mkswap and swapon
    窗体之间传值的方法
    扩展方法,
    反射 type 的基本用法,动态加载插件
  • 原文地址:https://www.cnblogs.com/bravolove/p/5883195.html
Copyright © 2020-2023  润新知