1.首先聊聊Cookie
cookie:
public class SetCookieServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);//调入当前类的doget方法
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
Cookie pedCookie=new Cookie("password","root");
pedCookie.setMaxAge(-1);
//-1表示此cookie为永久响应
response.addCookie(pedCookie);
Cookie gwlCookie = new Cookie("gwl","lxj");
gwlCookie.setMaxAge(60);
response.addCookie(gwlCookie);
Cookie wcCookie = new Cookie(URLEncoder.encode("旺财","UTF-8"),"lxj");
gwlCookie.setMaxAge(60);
response.addCookie(gwlCookie);
//服务端从客户端取值
PrintWriter writer=response.getWriter();
Cookie[] cookies = request.getCookies();
if(cookies !=null){
writer.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if(cookie.getName().equals("gwl")){
writer.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));
}
}
}else {
writer.write("这是你第一次访问");
}
writer.println("<h1>cookie写入成功~</h1>");
}
}
2.聊聊Session
什么是session:
public class MySessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
// 操作 Session,尝试从客户端获取一个 session,如果获取
// 失败,这新创建一个session信息
HttpSession session = request.getSession();
//服务器做校验
String sessionId = session.getId();
writer.println("<h1>欢迎访问~</h1>");
writer.println(String.format("<h3>SessionID:%s</h3>",
sessionId));
writer.println("<hr>"); // 输出分隔线
// 打印 Session 的创建时间
writer.println("Session 创建时间:"+ LocalDateTime.ofInstant(Instant.ofEpochMilli(session.getCreationTime()), ZoneId.systemDefault()));
// 打印 Session 的最后访问时间
writer.println(String.format("<p></p>Session 最后访问时间:%s<p></p>",
LocalDateTime.ofInstant(Instant.ofEpochMilli(session.getLastAccessedTime()), ZoneId.systemDefault())));
// 会话 key 值定义
String sessionKey = "countkey";
// 判断当前会话信息session是否为新的会话信息
if(session.isNew() ||
session.getAttribute(sessionKey)==null){
// 表示第一次使用 session 对象
session.setAttribute(sessionKey,1);
writer.println("访问次数:1");
}else{
// 非第一次访问
int count =(int)session.getAttribute(sessionKey);
count++;
// 更新 session 信息
session.setAttribute(sessionKey,count);
writer.println("访问次数:"+count);
}
// 移除属性
// session.removeAttribute("countkey");
// //设置过期
// session.invalidate();
}
}
Sesion和Cookie的区别:
使用场景: