JSP中Cookie案例改造一下

mac2026-04-14  2

<%@ page import="java.net.URLDecoder" %> <%@ page import="java.util.Date" %> <%@ page import="java.text.SimpleDateFormat" %> <%@ page import="java.net.URLEncoder" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>记住访问时间JSP</title> </head> <body> <% /* //设置响应的消息体的数据格式及编码 response.setContentType("text/html;charset=utf-8");*/ //①获取所有的Cookie Cookie[] cookies = request.getCookies(); boolean flag = false; //没有cookie为lastTime //②遍历Cookie数组 if ((cookies != null) & (cookies.length > 0)) { for (Cookie cookie : cookies) { //③获取cookie的名称 String name = cookie.getName(); //④判断名称是否是:lastTime if ("lastTime".equals(name)) { flag = true; //找到lastTime的cookie为true //有该cookie,不是第一次访问 //先获取前一次访问的cookie的value值 //响应数据 //获取cookie的value值,时间 String value = cookie.getValue(); System.out.println("解码前:" + value); //URL解码 value = URLDecoder.decode(value, "utf-8"); System.out.println("解码后:" + value); %> <%--out.write("<h1>欢迎回来,你上次访问时间为:" + value + "</h1>");--%> <%-- 阶段代码片面段 --%> <h1>欢迎回来,你上次访问时间为::<%= value%> </h1> <form action="#" method="post"> <table border="1" width="250"> <tr> <td><label for="username">用户名</label></td> <td><input type="text" name="username" id="username" ></td> </tr> <tr> <td><label for="password">密码</label></td> <td><input type="text" name="username" id="password" ></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" name="登录" value="登录"></td> </tr> </table> </form> <% //再设置cookie的value值 //获取当前时间的字符串,重新设置cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); //解析时间格式 System.out.println("编码前:" + str_date); //URL编码 str_date = URLEncoder.encode(str_date, "utf-8"); System.out.println("编码后:" + str_date); cookie.setValue(str_date); //设置cookie的存活时间; cookie.setMaxAge(60 * 60 * 24 * 30); //一个月 response.addCookie(cookie); break; } } } if (cookies == null || cookies.length == 0 || flag == false) { //没有lastTime 表示第一次访问 //设置cookie的value值 //获取当前时间的字符串,重新设置cookie的值,重新发送cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); String str_date = sdf.format(date); //解析时间格式 System.out.println("编码前:" + str_date); //URL编码 str_date = URLEncoder.encode(str_date, "utf-8"); System.out.println("编码后:" + str_date); Cookie cookie = new Cookie("lastTime", str_date); cookie.setValue(str_date); //设置cookie的存活时间; cookie.setMaxAge(60 * 60 * 24 * 30); //一个月 response.addCookie(cookie); %> <%-- out.write("<h1>您好,欢迎您是首次访问 </h1>");--%> <%-- 在这里使用html标签可以 新的JSP写法 ——截断 --%> <h1>您好,欢迎您是首次访问 </h1> <span></span> <% } %> </body> </html>

最新回复(0)