文章目录
Cookie Session 和 项目小模版
1. Session
1.1 Session 销毁操作
/**
* http://localhost:8080/Day41/sessionCreate
*
* @author Anonymous 2022/6/14 10:03
*/
@WebServlet("/sessionCreate")
public class SessionCreate extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
System.out.println("Session ID : " + session.getId());
Cookie cookie = new Cookie("JSESSIONID", session.getId());
// Cookie 和 Session 有效时间
cookie.setMaxAge(20);
session.setMaxInactiveInterval(20);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
/**
* @author Anonymous 2022/6/14 10:03
*/
@WebServlet("/sessionDestroy")
public class SessionDestroy extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
1. 有对应 Session 获取
2. 没有对应 Session 返回 null
*/
HttpSession session = req.getSession(false);
if (session != null) {
System.out.println("Destroy Session ID : " + session.getId());
// Session 被销毁
session.invalidate();
/*
创建一个新的 Cookie 对象, Cookie-name:JSESSIONID Cookie-value 为了节约资源
未存储任何数据,为空字符
使用当前 Cookie 对象,设置有效时间为 0,销毁浏览器对应 Cookie 数据
*/
Cookie cookie = new Cookie("JSESSIONID", "");
cookie.setMaxAge(0);
resp.addCookie(cookie);
} else {
System.out.println("Session Not Found!!!");
}
}
}
1.2 Session 域对象特征
/**
* @author Anonymous 2022/6/14 10:28
*/
@WebServlet("/sessionAttr")
public class SessionAttribute extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
ArrayList<String> list = new ArrayList<>();
list.add("油焖大虾");
list.add("大盘鸡");
list.add("卤牛肉");
list.add("酱牛肉");
list.add("蛋炒饭");
list.add("烤羊排");
list.add("蒜香鸡翅");
list.add("烤羊肉串");
HashMap<String, Object> map = new HashMap<>(5);
map.put("麻辣虾尾", "郑喜旺老店");
map.put("地锅鸡", "淼庄地锅鸡 行云路郑航路交叉口向西50米路南");
map.put("羊肉串", "老马烧烤 京广中路保全街向东300米路北");
map.put("炒拉条", "拉条烧烤城 大学路淮河路交叉口西北角");
map.put("火锅", "京广中路保全街向东100米路南 问大哥");
session.setAttribute("list", list);
session.setAttribute("map", map);
}
}
/**
* @author Anonymous 2022/6/14 10:28
*/
@WebServlet("/test1")
public class TestSession1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(false);
if (session != null) {
System.out.println("TestSession1");
@SuppressWarnings("unchecked")
List<String> list = (List<String>) session.getAttribute("list");
list.forEach(System.out::println);
System.out.println("--------------------");
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) session.getAttribute("map");
map.forEach((key, value) -> System.out.println(key + ":" + value));
System.out.println("--------------------");
// session.setAttribute("TestSession1-Value", "我饿了");
System.out.println(session.getAttribute("TestSession1-Value"));
}
}
}
2. Cookie 和 Session 案例
2.1 Cookie 记录用户上一次登陆时间
1. 如果用户第一次访问
给予用户对应 Cookie 数据,同时欢迎用户
2. 用户之后访问
提示用户上一次访问时间,同时欢迎用户
设置 Cookie
Cookie-name: lastTime
Cookie-value: 2022/06/14_11:32:15
package com.qfedu.b_cookieAndSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;
/**
* 条件罗列
* 1. 之前有过访问记录
* a. Cookie != null
* b. Cookie-name.equals("lastTime") == true
* 2. 没有访问记录
* 第一种情况:
* Cookie == null
* 第二种情况:
* Cookie != null
* Cookie-name.equals("lastTime") == false
*
* @author Anonymous 2022/6/14 11:32
*/
@WebServlet("/lastTime")
public class LastTimeCookie extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// 1. 通过 Request 对象获取用户请求 Cookie 数据内容
Cookie[] cookies = req.getCookies();
String msg = null;
/*
JDK 1.8 以上
Stream 流 + Lambda 表达式 + 函数式接口 + 方法引用
数组 ==> Stream 流(流水线) ==> Stream<Cookie> ==> anyMatch 有任何的匹配项
==> Predicate<? super T> predicate 判断接口
*/
boolean flag = cookies != null && Arrays
.stream(cookies)
.anyMatch(cookie -> "lastTime".equals(cookie.getName()));
// flag ==> true 表示用户之前来过
if (flag) {
/*
Arrays.stream ==> Stream流 ==> filter过滤 Predicate<? super T> predicate 判断接口
==> collect ==> List<Cookie> ==> get(0) ==> Cookie ==> getValue ==> String value
*/
String value = Arrays
.stream(cookies)
.filter(cookie -> "lastTime".equals(cookie.getName()))
.collect(Collectors.toList())
.get(0)
.getValue();
msg = "<h1>您上一次的登陆时间 :" + value + "</h1>";
} else {
msg = "<h1>欢迎您第一次来到本站!!!</h1>";
}
// 创建 lastTime Cookie 存储当前时间
Cookie cookie = new Cookie("lastTime", new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss").format(new Date()));
cookie.setMaxAge(60 * 60 * 24 * 15);
// 发送 Cookie 和 msg 到 浏览器
resp.addCookie(cookie);
resp.getWriter().append(msg);
}
}
2.2 自动登陆完成
1. Cookie 设置
存储 Session ID 的 Cookie
Cookie-name: JSESSIONID
Cookie-value : Session ID
2. Session 情况
Session Attribute 中存储用户名
用户第一次登陆
1. Session 存储用户名
2. Cookie 存储 Session ID
退出登陆:
1. 销毁 Session
2. 销毁对应 Cookie
3. 项目 学生管理项目 JavaWEB 版
3.1 功能概述
主要功能:
1. 添加学生
2. 展示所有学生
3. 修改学生信息
4. 删除学生信息
5. 按照学生姓名搜索信息
6. 按照指定范围过滤学生信息
7. 按照指定条件排序学生信息
数据表结构
CREATE TABLE `student`
(
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`age` int(11) NOT NULL,
`gender` tinyint(1) NOT NULL,
`score` float(5, 2) NOT NULL,
`address` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8;
3.2 添加学生操作
3.3 所有学生列表
3.4 删除学生信息
3.5 修改学生信息
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-21QkRC7j-1656147622577)(img/04-更新学生信息流程.png)]