cookie和Session
一、cookie
1.什么是Cookie?
1、Cookie是服务器 通知 客户端 保存键值对 的一种技术。
2、客户端有了cookie后,每次请求都发送给服务器。
3、每个cookie的大小不能超过4kb
2.如何创建Cookie
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6ECaFIdv-1635346813349)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images )]
package cookie.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=new Cookie("key1","value1");
resp.addCookie(cookie);
resp.getWriter().write("cookie创建成功!");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SbDJJObg-1635346813354)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
3.如何获取Cookie
服务器获取客户端的Cookie只需要一行代码: req.getCookies():Cookie[]
package cookie.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies= req.getCookies();
for(Cookie cookie : cookies){
resp.getWriter().write("Cookie["+cookie.getName()+"="+cookie.getValue()+"]<br>");
}
}
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=new Cookie("key1","value1");
resp.addCookie(cookie);
resp.getWriter().write("cookie创建成功!");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AmuAnHyx-1635346813357)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
4.Cookie值的修改
方案一:
1、先创建一个要修改的同名的Cookie对象 2、在构造器,同时赋于新的Cookie值。 3、调用response.addCookie( Cookie );
package cookie.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet {
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=new Cookie("key1","newvalue1");
resp.addCookie(cookie);
resp.getWriter().write("key1的cookie已经修改好了!");
}
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies= req.getCookies();
for(Cookie cookie : cookies){
resp.getWriter().write("Cookie["+cookie.getName()+"="+cookie.getValue()+"]<br>");
}
}
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=new Cookie("key1","value1");
resp.addCookie(cookie);
resp.getWriter().write("cookie创建成功!");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xK8UuoFa-1635346813359)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
方案二、260 略
5. 浏览器查看cookie
i.谷歌浏览器查看cookie
Fn+F12
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bQKdA6il-1635346813360)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
ii.火狐浏览器查看cookie
略
6.Cookie生命控制
Cookie 的生命控制指的是如何管理cookie 什么时候被销毁(删除)
setMaxAge() 正数,表示在指定的秒数后过期 负数,表示浏览器一关,cookie就会被删除(默认值是-1) 零,表示马上删除cookie
*i. 设置一个存活x长时间的cookie
protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=new Cookie("life3600","life3600");
cookie.setMaxAge(60*60);
resp.addCookie(cookie);
resp.getWriter().write("已经创建了一个存活1小时的cookie");
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0BpEu4jV-1635346813362)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
ii. 设置存活时间
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=new Cookie("defaultLife","defaultLife");
cookie.setMaxAge(-1);
resp.addCookie(cookie);
}
iii. 删除某个cookie
(需要创建一个CookieUtils.java文件来调用findcookie方法——略)
protected void delateNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=CookieUtils.findcookie("key2",req.getCookies());
if (cookie!=null){
cookie.setMaxAge(0);
resp.addCookie(cookie);
resp.getWriter().write("key2的cookie已经被删除了!");
}
}
7.Cookie有效路径Path的设置
Cookie 的 path属性可以有效的过滤哪些Cookie可以发送给服务器。哪些不发。
path属性是通过请求的地址来进行有效的过滤。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-noeUCUqG-1635346813363)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie=new Cookie("path1","path1");
cookie.setPath(req.getContextPath()+"/abc");
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有path路径的cookie");
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x4Rr1onX-1635346813364)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images )]
*8.Cookie练习——免输入 用户名、密码 登录
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-99CzbPoc-1635346813365)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
<%--
Created by IntelliJ IDEA.
User: 樊雨欣
Date: 2021/10/13
Time: 17:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录页面</title>
</head>
<body>
<form action="/onServlet1" method="post">
<%--注意这里的value ,不论username还是password都用cookie--%>
用户名:<input type="text" name="username" value="${cookie.username.value}">
</br>
密码:<input type="password" name="password" value="${cookie.password.value}">
</br>
<button > 登录</button>
</form>
${cookie.username.value}</br>
${cookie.password.value}
</body>
</html>
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;
@WebServlet(name = "onServlet1")
public class onServlet1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String username= request.getParameter("username");
String password= request.getParameter("password");
if ("fan1116".equals(username)&&"123456".equals(password)){
Cookie cookie=new Cookie("username",username);
System.out.println(password);
Cookie cookie2=new Cookie("password",password);
cookie.setMaxAge(60*60*2);
cookie2.setMaxAge(60*60*2);
response.addCookie(cookie);
response.addCookie(cookie2);
response.getWriter().write("恭喜你,登陆成功!");
}else{
response.getWriter().write("登录失败。");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
*二、session
1.什么是session会话
1、session就一个接口( HttpSession) 。 2、Session就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个Session会话。 4、 Session会话中,我们经常用来保存用户登录之后的信息。
*2.如何创建session和获取(id)
如何创建和获取session。它们的API是一样的。
request.getSession() 第一次调用是: 创建session会话 之后调用都是: 获取前面创建好的session会话对象。
isNew();判断到底是不是刚创建出来的(新的) true表示刚创建 false表示获取之前创建
每个会话都有一个身份证号。也就是ID值。而且这个ID是唯一的。
getld()得到session的会话id值。
package cookie.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet {
protected void creatOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
boolean isNew =session.isNew();
String id=session.getId();
resp.getWriter().write("得到的session的id"+id+"</br>");
resp.getWriter().write("得到的session是否是新创建的:"+isNew+"</br>");
}
}
运行截图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Haq9BmAl-1635346813366)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images )]
*3. session域数据的存取
package cookie.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet {
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key1","value1");
resp.getWriter().write("已经往session中保存了数据!");
}
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object attribute= req.getSession().getAttribute("key1");
resp.getWriter().write("从session中获取的key1的数据是"+ attribute);
}
protected void creatOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
boolean isNew =session.isNew();
String id=session.getId();
resp.getWriter().write("得到的session的id"+id+"</br>");
resp.getWriter().write("得到的session是否是新创建的:"+isNew+"</br>");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Fkkl7WBZ-1635346813367)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-36JlO1pH-1635346813368)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
4. session 生命周期控制
设置:public void setMaxInactivelInhterval(int interval)
? 设置Session的超时时间〈以秒为单位),超过指定的时长,Ssession就会被销毁。
获取:public int getMaxInactivelnterval()获取session的超时时间
马上销毁:public void invalidate (让当前session会话马上超时无效)
session的默认时长为30min , Tomcat 中默认的
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JePznYrc-1635346813369)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
1.改变所有的session时长
(在web.xml中修改)
<session-config>
<session-timeout>30</session-timeout>
</session-config>
2.修改某个文件的session时长
package cookie.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionServlet extends BaseServlet {
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int maxInactiveInterval= req.getSession().getMaxInactiveInterval();
resp.getWriter().write("默认session时长为:"+maxInactiveInterval+"秒");
}
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setMaxInactiveInterval(3);
resp.getWriter().write("当前session已经设置为3秒后超时");
}
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.invalidate();
resp.getWriter().write("session已经设置为马上销毁");
}
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key1","value1");
resp.getWriter().write("已经往session中保存了数据!");
}
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object attribute= req.getSession().getAttribute("key1");
resp.getWriter().write("从session中获取的key1的数据是"+ attribute);
}
protected void creatOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
boolean isNew =session.isNew();
String id=session.getId();
resp.getWriter().write("得到的session的id"+id+"</br>");
resp.getWriter().write("得到的session是否是新创建的:"+isNew+"</br>");
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ShGkh820-1635346813370)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8WNLR4qN-1635346813371)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images!在这里插入图片描述 )]
5. 浏览器和 Session之间关联的技术内幕
Session技术,底层其实是基于cookie技术来实现的。
nse resp) throws ServletException, IOException {
HttpSession session=req.getSession();
//判断session会话,是否是新的
boolean isNew =session.isNew();
//获取session 会话的唯一标识
String id=session.getId();
resp.getWriter().write("得到的session的id"+id+"</br>");
resp.getWriter().write("得到的session是否是新创建的:"+isNew+"</br>");
}
}
[外链图片转存中...(img-ShGkh820-1635346813370)]
[外链图片转存中...(img-8WNLR4qN-1635346813371)]
# 5. 浏览器和 Session之间关联的技术内幕
> Session技术,底层其实是基于cookie技术来实现的。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vG8NsxcQ-1635346813372)(C:\Users\86173\AppData\Roaming\Typora\typora-user-images\![在这里插入图片描述](https://img-blog.csdnimg.cn/f31aa03bd5824edc809f230239630f06.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5oiQ5LqL5LiN6Laz7pCZ,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
)]
|