Cookie&Seesion
作者:互联网
Cookie&Seesion
一、会话
会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称为会话
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,这就是有状态会话
一个网站,怎么证明你来过
- 服务端给客户端一个信件,客户端下次访问服务端带上信件就可以了—>Cookie
- 服务端登记你来过,下次你来的时候我来匹配你—>Seesion
二、保存会话的两种技术
1、Cookie
- 客户端技术(响应,请求)
2、Seesion
- 服务器技术,利用这个技术,可以保存用户的会话信息。我们可以把信息或者数据放在Seesion中
常见场景:网站登录之后,你下次不用再登录了,第二次访问就直接上去了
三、Cookie
- 从请求中拿到cookie信息
- 服务器响应给客户端cookie
Cookie[] cookies = req.getCookies(); //获取cookie
cookie.getName(); //获得cookie中的key
cookie.getValue();//获得cookie中的value
new Cookie("lastLogonTime", System.currentTimeMillis()+"");//新建一个cookie
cookie.setMaxAge(24*60*60);//设置cookie的有效期
resp.addCookie(cookie);//响应给客户端一个cookie
cookie:一般会保存在本地的用户目录下的appdata;
案例
package com.jhoves.servlet;
import javax.servlet.ServletException;
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.io.PrintWriter;
import java.util.Date;
//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器,告诉你,你来的时间,把这个时间封装成为一个信件,你下次带来,我就知道你来了
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
//cookie,服务器端从客户端获取
Cookie[] cookies = req.getCookies(); //这里返回数组,说明cookie存在多个
//判断cookie是否存在
if (cookies != null){
//如果存在怎么办
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if(cookie.getName().equals("lastLogonTime")){
//获取cookie中的值
long lastLogonTime = Long.parseLong(cookie.getValue());
Date date = new Date(lastLogonTime);
out.write(date.toLocaleString());
}
}
}else{
out.write("这是您第一次访问本站");
}
//服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastLogonTime", System.currentTimeMillis()+"");
resp.addCookie(cookie);
//cookie有效期为一天
cookie.setMaxAge(24*60*60);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>CookieDemo01</servlet-name>
<servlet-class>com.jhoves.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo01</servlet-name>
<url-pattern>/c1</url-pattern>
</servlet-mapping>
一个网站cooki是否存在上限!(聊聊细节)
- 一个cookie只能保存一个信息;
- 一个web站带你可以给浏览器发送多个cookie,最多存放20个cookie;
- cookie大小有限制,为4kb;
- 300个cookie是浏览器的上限;
删除Cookie:
- 不设置有效期,关闭浏览器,自动失效;
- 设置有效期时间为0;
编码解码:
//编码
URLEncoder.encode("文字","utf-8")
//解码
URLDecoder.decode(cookie.getValue(),"utf-8")
案例
package com.jhoves.servlet;
import javax.servlet.ServletException;
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.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
//中文数据传递
public class CookieDemo03 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//Cookie,服务器从客户端获取
Cookie[] cookies = req.getCookies(); //这里返回数组,说明cookie存在多个
PrintWriter out = resp.getWriter();
//判断cookie是否存在
if(cookies!=null){
out.write("你上一次访问的用户是:");
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
//获取cookie的名字
if (cookie.getName().equals("name")){
//解码
out.write(URLDecoder.decode(cookie.getValue(),"utf-8"));
}
}
}else{
out.write("这是您第一次访问本站");
}
//编码
Cookie cookie = new Cookie("name", URLEncoder.encode("文字","utf-8"));
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>CookieDemo03</servlet-name>
<servlet-class>com.jhoves.servlet.CookieDemo03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo03</servlet-name>
<url-pattern>/c3</url-pattern>
</servlet-mapping>
四、Session(重点)
什么是Seesion:
- 服务器会给每一个用户(浏览器)创建一个Session对象
- 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个session就存在
- 用户登录之后,整个网站它都可以访问 -->保存用户的信息,保存购物车的信息...
Session和Cookie的区别:
- Cookie把用户的数据写给用户浏览器,浏览器保存(可以保存多个)
- Session把用户的数据写到用户独占的Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
- Session对象由服务器创建
使用场景:
- 保存一个登录用户的信息
- 购物车信息
- 在整个网站中经常会使用的数据我们将他保存在Session中
使用Session:
package com.jhoves.pojo;
//创建了一个Person对象
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-16");
resp.setCharacterEncoding("utf-16");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name",new Person("俊鸿",1));
//获取Session的id
String sessionId = session.getId();
//判断session是否为新创建的
if(session.isNew()){
resp.getWriter().write("session创建成功,ID为:"+ sessionId);
}else{
resp.getWriter().write("session已经在服务器中存在了ID为:"+ sessionId);
}
//Session创建的时候做了什么事情
// Cookie cookie = new Cookie("JSESSIONID",sessionId);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<servlet>
<servlet-name>SessionDemo01</servlet-name>
<servlet-class>com.jhoves.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo01</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
- 手动注销Session
package com.jhoves.servlet;
import com.jhoves.pojo.Person;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SessionDemo03 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-16");
resp.setCharacterEncoding("utf-16");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
- 会话自动过期:web.xml中配置
<!--设置Session默认的失效的失效时间-->
<session-config>
<!--1分钟后Session自动失效,以分钟为单位-->
<session-timeout>1</session-timeout>
</session-config>
标签:resp,req,cookie,Seesion,import,Cookie,servlet 来源: https://www.cnblogs.com/JHoves/p/15977925.html