
回顾
1. ServletContext域对象
api
setAttribute()
getAttribute()
removeAttribute()
生命周期
在tomcat启动,web项目加载时,创建
在tomcat关闭或web项目卸载时,销毁
与项目共存亡
2. ServletContext获取资源真实路径
后期获取web项目内的资源都是用这个方案
getRealPath("/") 相当web目录
3. Response重定向
response.sendRedirect("/项目名/servlet资源地址")
特点
1.地址栏发送改变
2.是二次请求
3.跳转到服务器外部资源
4.不能使用request域共享数据
4. Response响应中文
一统天下:一个命令设置服务器和客户端的编码方式
response.setContentType("text/html;charset=utf-8")
3. 综合案例
点击切换验证码
文件下载
二个头二个流
Cookie
今日目标
1. 会话概述
2. cookie【重点】
3. 综合案例
一 会话概述
1.1 什么是会话?
日常生活中:从拨通电话到挂断电话之间的一连串你问我答的过程就是一个会话。
B/S架构中:从浏览器第一次给服务器发送请求时,建立会话;直到有一方断开,会话结束。
一次会话:包含多次请求响应。

1.2 会话技术
问题:Http是一个无状态协议,同一个会话的连续两个请求相互独立,彼此并不了解
作用:用于==存储==浏览器与服务器在请求和响应过程中产生的==数据==
客户端会话技术:cookie
服务器端会话技术:session

二 Cookie【重点】
2.1 概述
Cookie作用:在一次会话的多次请求之间共享数据,将数据保存到客户端(浏览器)
jd购物车

2.2 快速入门
1. 设置数据到cookie中
// 1.创建cookie对象,设置数据
Cookie cookie = new Cookie(String name,String value);
// 2.通过response,响应(返回)cookie
response.addCookie(cookie);
2. 从cookie中获取数据
// 1.通过request对象,接收cookie数组
Cookie[] cookies = request.getCookies();
// 2.遍历数组
@WebServlet("/SetServlet")
public class SetServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.创建cookie对象,设置数据
Cookie cookie = new Cookie("name","jack");
// 2.通过response,响应(返回)cookie
response.addCookie(cookie);
}
}
@WebServlet("/GetServlet")
public class GetServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.通过request对象,接收cookie数组
Cookie[] cookies = request.getCookies();
// 2.遍历数组
if(cookies!=null){
for (Cookie c : cookies) {
String name = c.getName();
String value = c.getValue();
System.out.println(name + " : " + value);
}
}
}
}
2.3 工作原理
基于HTTP协议:请求头cookie 和 响应头 set-cookie

2.4 Cookie细节
2.4.1 服务器发送多个Cookie?
* 答案是可以的
// 1. 创建多个cookie对象
Cookie cookie1 = new Cookie("name","lucy");
Cookie cookie2 = new Cookie("age","18");
// 2. 通过response响应多个
response.addCookie(cookie1);
response.addCookie(cookie2);
@WebServlet("/MultipleCookie")
public class MultipleCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 创建多个cookie对象
Cookie cookie1 = new Cookie("name","lucy");
Cookie cookie2 = new Cookie("age","18");
// 2. 通过response响应多个
response.addCookie(cookie1);
response.addCookie(cookie2);
}
}
2.4.2 Cookie在浏览器保存时间?
* 默认情况下
浏览器关闭(会话结束),cookie销毁(内存)
* 设置cookie的存活时间
cookie.setMaxAge(int second); -- 单位是秒
正数:指定存活时间,持久化浏览器的磁盘中,到期后自动销毁
负数:默认浏览器关闭,cookie销毁
零:立即销毁(自杀)
@WebServlet("/MaxAgeCookie")
public class MaxAgeCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.创建cookie对象
Cookie cookie = new Cookie("product", "xiaomi10");
// 2.设置cookie存活时间
// cookie.setMaxAge(-1); // 默认值,浏览器关闭自动销毁
// cookie.setMaxAge(60);// 存活30秒,到期自动销毁
cookie.setMaxAge(0); // 立即销毁...
//3. response响应cookie
response.addCookie(cookie);
}
}
2.4.3 Cookie是否可以存储中文?
* tomcat8之前的版本,不支持中文
URLEncoder 编码
URLDecoder 解码
* tomcat8以后的版本,支持中文...
Rfc6265Cookie规范,不允许使用 分号、空格、逗号等一些特殊符号...
@WebServlet("/EncodeCookie")
public class EncodeCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String product = "华为荣耀 30X,";
product= URLEncoder.encode(product, "UTF-8");
// 1.创建cookie对象
Cookie cookie = new Cookie("product", product);
// 2.response响应cookie
response.addCookie(cookie);
}
}
@WebServlet("/GetServlet")
public class GetServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.通过request对象,接收cookie数组
Cookie[] cookies = request.getCookies();
// 2.遍历数组
if(cookies!=null){
for (Cookie c : cookies) {
String name = c.getName();
String value = c.getValue();
// 解码
value = URLDecoder.decode(value, "UTF-8");
System.out.println(name + " : " + value);
}
}
}
}
2.4.4 Cookie共享数据的范围?
① 在一个tomca服务器中,部署了多个web项目,那么这些web项目的Cookie能否共享?
* 默认情况下不可以
默认cookie的携带路径,是当前设置cookie的serlvet父路径。。。。
设置cookie:http://localhost:8080/day11_cookie/EncodeCookie
默认携带路径:http://localhost:8080/day11_cookie
* 指定cookie的携带路径
cookie.setPath(String path);
举例:
cookie.setPath("/");
/ 相当于 http://localhost:8080/
此cookie携带路径
访问
http://localhost:8080/day11_cookie
http://localhost:8080/day10_response
* 注意
cookie的携带路径不同,名称可以重复....
* 课下练习题
设置cookie
http://localhost:8080/day11_cookie/aa/SetCookie
接收cookie
http://localhost:8080/day11_cookie/bb/GetCookie
默认情况下,是否能获取aa目录下的cookie数据?
答案是不可以....
在当前项目下共享cookie
cookie.setPath("/项目名")

@WebServlet("/PathCookie")
public class PathCookie extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String product = "小米10";
product = URLEncoder.encode(product, "UTF-8");
// 1.创建cookie对象
Cookie cookie = new Cookie("product", product);
// 2.设置cookie的携带路径
cookie.setPath("/");
// 3.response响应cookie
response.addCookie(cookie);
}
}
② 不同tomcat服务器之间Cookie能否共享?
* 默认情况下不可以
* 多个服务器之间的数据共享cookie,需要在同一个一级域名下
cookie.setDomain(".jd.com")

2.5 Cookie特点
1. cookie存储数据都在客户端(浏览器)
2. cookie的存储数据只能是字符串
3. cookie单个大小不能超过4KB
4. 同一个域名下cookie数量不能超过50个
5. cookie路径不同,可以重名出现
6. cookie存储的数据不太安全
三 综合案例【大作业】
3.1 用户上次访问记录
需求
访问一个Servlet,如果是第一次访问,则提示:您好,欢迎您的到来。
如果不是第一次访问,则提示:欢迎回来,您上次访问时间为: xxxx。
3.1.1 需求分析

3.1.2 代码实现
① LastTimeServlet
@WebServlet("/LastTimeServlet")
public class LastTimeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 1.接收cookie数组,取出指定名称cookie对象
Cookie cookie = CookieUtils.findByName("last_time", request.getCookies());
// 2.判断
if (cookie == null) {
// 不存在
response.getWriter().write("<h1>欢迎您,首次访问....</h1>");
} else {
// 存在
String value = cookie.getValue();
response.getWriter().write("<h1>欢迎回来,您上次访问时间:" + value + "</h1>");
}
// 3.创建cookie对象,记录本次访问时间
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日-HH:mm:ss");
String currentTime = simpleDateFormat.format(new Date());
cookie = new Cookie("last_time", currentTime);
// 4.设置cookie存活1年
cookie.setMaxAge(60 * 60 * 24 * 365);
// 5.response响应cookie
response.addCookie(cookie);
}
}
② CookieUtils
public class CookieUtils {
/*
根据指定名称,查找cookie对象
*/
public static Cookie findByName(String name, Cookie[] cookies) {
// 非空判断
if (cookies != null && cookies.length > 0) {
// 遍历
for (Cookie cookie : cookies) {
// 判断是否有指定名称的cookie
if (name.equals(cookie.getName())) {
return cookie;
}
}
}
// 没找到返回null
return null;
}
}
3.2 Jsp初体验
- Java服务器端页面(Java Server Pages)
- 简单来说:一个特殊的页面,即可定义html标签,又可以定义java代码
- 作用:简化书写,展示动态页面
- 本质:是servlet
* 脚本:Jsp通过脚本方式来定义java代码
<% java代码 %> 就相当于servlet中service方法...
* 内置对象:在Jsp页面中不需要获取和创建,可以直接使用的对象
request
response
out
注意:在jsp响应内容,使用out

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>demo</title>
</head>
<body>
<h3>我是标题</h3>
<table border="1" width="200" align="center">
<tr>
<td>我是静态资源...</td>
</tr>
</table>
<%
System.out.println("我是jsp哈哈哈...");
request.getServletContext();
out.write("out输出的hehe");
// response.getWriter().write("hehe");
%>
</body>
</html>
课下作业:使用jsp编写案例:用户上次访问记录》。。

3.3 商品浏览记录【第一遍根据画图找这抄】
需求
做一个商品页面,当我们访问后,在页面上点击查看商品浏览记录后,可以查看到以前浏览过的商品信息
3.3.1 需求分析

3.3.2 代码实现
① goods.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>goods</title>
</head>
<body>
<h3>商品列表</h3>
<a href="/day11_cookie/GoodsInfoServlet?name=小米10">小米10</a> <br>
<a href="/day11_cookie/GoodsInfoServlet?name=华为P40">华为P40</a> <br>
<a href="/day11_cookie/GoodsInfoServlet?name=iphoneSE">iphoneSE</a> <br>
<a href="/day11_cookie/GoodsInfoServlet?name=锤子T2">锤子T2</a> <br>
</body>
</html>
② GoodsInfoServlet
@WebServlet("/GoodsInfoServlet")
public class GoodsInfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); // 请求解码
response.setContentType("text/html;charset=utf-8"); // 响应编码
// 1.获取请求参数 name 小米10
String product = request.getParameter("name");
// 2.展示当前商品详情
response.getWriter().write("您当前浏览的商品为:" + product);
// 3.获取指定名称cookie对象
Cookie cookie = CookieUtils.findByName("goods_name", request.getCookies());
// 4.判断是否存在...
if (cookie == null) {
// 5.如果不存在,将当前商品设置到cookie对象中...
cookie = new Cookie("goods_name", product);
} else {
// 6.如果有,将浏览记录取出,格式:小米10-华为P40
String value = cookie.getValue();
// 7.判断当前商品是否在此cookie中
List<String> list = Arrays.asList(value.split("-"));
// 8.如果不包含,追加
if (!list.contains(product)) {
value = value + "-" + product; // 格式:小米10-华为P40
}
// 9.将value,重置到cookie中
cookie = new Cookie("goods_name", value);
}
// 10.通过response响应到浏览器
// 设置存活时间 为1年
cookie.setMaxAge(60 * 60 * 24 * 365);
response.addCookie(cookie);
// 11.制作a标签,实现记录浏览商品功能
response.getWriter().write("<br><a href='/day11_cookie/goods.html'>继续浏览</a>");
// 12.制作a标签,实现查看浏览记录功能
response.getWriter().write("<br><a href='/day11_cookie/history.jsp'>浏览记录</a>");
}
}
③ history.jsp
<%@ page import="cn.itcast.f_lasttime.CookieUtils" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>history</title>
</head>
<body>
<%
// java的代码...
// 1.获取指定名称cookie对象
Cookie cookie = CookieUtils.findByName("goods_name", request.getCookies());
// 2.判断是否存在浏览记录
if(cookie == null){
// 没有提示
out.write("暂无浏览记录....");
}else{
// 有的话,遍历显示
out.write("浏览记录如下:<br>");
String value = cookie.getValue(); // 格式:小米10-华为P40
for (String product : value.split("-")) {
out.write(product+"<br>");
}
}
%>
</body>
</html>
网友评论