3、cookie涉及的常用方法
代码演示:
@WebServlet("/servletDemo01") public class ServletDemo01 extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.通过响应对象写出提示信息 resp.setContentType("text/html;charset=UTF-8"); PrintWriter pw = resp.getWriter(); pw.write("欢迎访问本网站,您的最后访问时间为:
"); //2.创建cookie对象,用于记录最后访问时间 cookie cookie = new cookie("time",System.currentTimeMillis()+""); //3.设置最大存活时间 //cookie.setMaxAge(3600); cookie.setMaxAge(0); // 立即清除 //4.将cookie对象添加到客户端 resp.addcookie(cookie); //5.获取cookie cookie[] arr = req.getcookies(); for(cookie c : arr) { if("time".equals(c.getName())) { //6.获取cookie对象中的value,进行写出 String value = c.getValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); pw.write(sdf.format(new Date(Long.parseLong(value)))); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)