Cookie获取客户端信息及响应
2020-04-01 19:04
621 查看
个人博客地址https://nfreak-man.cn
在用户没有登录时,cookie常用来完成服务器对客户端的省份识别及一些设置的保存。
以下为一个简单的记录用户上次访问时间的功能。
@WebServlet("/cookieTest") public class CookieTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置响应的消息体的数据格式以及编码 response.setContentType("text/html;charset=utf-8"); //1.获取所有cookie Cookie[] cookies = request.getCookies(); boolean flag = false;//没有cookie为lastTime //2.遍历cookie数组 if (cookies != null && cookies.length > 0){ for (Cookie cookie : cookies) { //3.获取cookie的名称 String name = cookie.getName(); //4.判断名称是否是:lastTime if ("lastTime".equals(name)){ //有该cookie,不是第一次访问 flag = true; //响应数据 //获取cookie的value,时间 String value = cookie.getValue(); //URL解码 value = URLDecoder.decode(value,"utf-8"); response.getWriter().write("<h1>欢迎回来,您上次访问时间为:"+value+"<h1>"); //设置cookie的value //获取当前时间的字符串,重新设置cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss"); String str_date = sdf.format(date); //URL编码 str_date = URLEncoder.encode(str_date, "utf-8"); cookie.setValue(str_date); //设置cookie的存活时间 cookie.setMaxAge(60 * 60 * 24 * 30);//一个月 response.addCookie(cookie); break; } } } if (cookies == null || cookies.length == 0 || flag == false){ //没有,第一次访问 //设置cookie的value //获取当前时间的字符串,重新设置cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); //URL编码 str_date = URLEncoder.encode(str_date, "utf-8"); Cookie cookie = new Cookie("lastTime",str_date); //设置cookie的存活时间 cookie.setMaxAge(60 * 60 * 24 * 30);//一个月 response.addCookie(cookie); response.getWriter().write("<h1>您好,欢迎首次访问<h1>"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- [转载]js获取客户端time,cookie,url,ip,refer,user_agent信息
- IE浏览器中获取不到ZendFrame Work响应的Cookie头信息
- js获取客户端time,cookie,url,ip,refer,user_agent信息:
- 使用客户端httpClient携带cookie,模拟登陆网站,扒取html网页信息
- CAS客户端.NET集成单点登录获取不到登录用户信息的问题
- asp获取服务器信息大全(包括客户端证书信息)
- ASP.NET获取客户端IP/用户名等信息
- JS 客户端验证文件类型,获取图片信息
- .NET获取客户端信息
- ONVIF协议网络摄像机(IPC)客户端程序开发(8):获取设备基本信息
- CPC客户端离线升级失败,不能获取updatesipo信息,可能你的软件在线更新程序没有安装
- jsp中如何获取客户端的浏览器和操作系统信息
- Servlet获取客户端浏览器信息和客户端的操作系统
- asp.net获取客户端浏览器及主机信息
- ASP.NET获取客户端、服务器端基础信息集合
- 转:asp.net 获取客户端相关信息
- php 获取客户端的ip、地理信息、浏览器信息、本地真实ip
- 获取客户端 浏览器信息和操作系统信息
- JavaScript 获取客户端计算机硬件及系统信息
- request获取客户端浏览器的信息