本文主要是介绍P16 cookie,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
非重点。
获取上一次登录的时间
package com.Li.servlet;import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;//
public class CookieDemo01 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//服务器告诉你来的时间,把时间信息封装好。你下次来的时候带上,我就知道时间了//解决中文乱码问题req.setCharacterEncoding("utf-16");resp.setCharacterEncoding("utf-16");PrintWriter out = resp.getWriter();//前端输出//cookie服务器端从客户端获取Cookie[] cookies = req.getCookies();//获得cookie//判断Cookie是否存在if (cookies!=null){//如果存在out.write("你上次访问的时间是:");//输出显示在前端for (int i = 0; i < cookies.length; i++) {Cookie cookie = cookies[i];//将每一轮的cookie值拿出来赋给cookie//获取cookie的名字if (cookie.getName().equals("lastLoginTime")){//如果cookie数组中存有我们所要的lastLoginTime一样名字,进行下一步//获取cookie中的值//将cookie中的值(String)转换为时间的格式long lastLoginTime = Long.parseLong(cookie.getValue());//转化格式Date date = new Date(lastLoginTime);//转化格式System.out.println(date);//测试在后端输出out.write(date.toLocaleString());//输出显示在前端}}}else {out.write("这是您第一次访问");//输出显示在前端}//服务给客户端相应一个cookieCookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");//将System.currentTimeMillis()转换为Stringcookie.setMaxAge(60);//设置Cookie有效时间60s.即使关闭浏览器也可以生效的那种resp.addCookie(cookie);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
将cookie的保存时间设置为0s
package com.Li.servlet;import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;//删除cookie。将其有效时间设置为0
public class CookieDemo02 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//名字和Demo01的必须一样Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");//将System.currentTimeMillis()转换为Stringcookie.setMaxAge(0);//设置Cookie有效时间0sresp.addCookie(cookie);//前端可视化resp.getWriter().write("clean cookie succeed!");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}
还有web。xml配置。
这篇关于P16 cookie的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!