• 第一个Cookie应用


    Cookie应用:显示用户上次访问时间

    package com.itheima.cookie;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Date;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.itheima.myConstant;
    /**
     * Servlet implementation class CookieDemo2
     */
    @WebServlet(
    		urlPatterns = { "/CookieDemo1" }, 
    		initParams = { 
    				@WebInitParam(name = "CookieDemo1", value = "com.itheima.cookie.CookieDemo1")
    		})
    /*
     * Cookie是客户端技术,程序把每个用户的数据以Cookie的形式写给用户的各自的浏览器,
     * 当用户使用浏览器再去访问服务器中的web资源时,这样,web资源处理的就是用户各自的数据了,
     * 在购物时,每个用户的数据都用各自的Cookie存储,互不影响。
     */
    public class CookieDemo1 extends HttpServlet {
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		//设置编码
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out=response.getWriter();//得到输出流,写提示信息
    		out.write("您上次访问的时间为");
    		//从客户端请求中获取指定的Cookie
    		Cookie[] cookies=request.getCookies();
    		for(int i=0;cookies!=null&&i<cookies.length;i++){
    			Cookie cookie=cookies[i];
    			if(myConstant.LAST_ACCESS_TIME.equals(cookie.getName())){
    				//输出值
    				long value=Long.parseLong(cookie.getValue());
    				out.println(new Date(value).toLocaleString());
    			}
    		}
    		//把当前的时间给客户端
    		Cookie c=new Cookie(myConstant.LAST_ACCESS_TIME,System.currentTimeMillis()+"");
    		c.setPath(request.getContextPath());
    		c.setMaxAge(10*24*60*60);//存活时间,默认为浏览器进程
    		response.addCookie(c);
    	}
    
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doGet(request,response);
    	}
    
    }
    
  • 相关阅读:
    select,epoll,poll比较(网络资源总结)
    c++(重载、覆盖、隐藏)
    TCP状态转换图
    TCP心跳 | TCP keepAlive
    回车、换行、空格的ASCII码值—(附ASCII码表)
    C++ dlopen mini HOWTO 一篇非常好的介绍
    shell十三问
    linux IPC消息队列 的内核限制
    C++ string 类常用函数
    const用法的解惑
  • 原文地址:https://www.cnblogs.com/lzzhuany/p/4701724.html
Copyright © 2020-2023  润新知