1. 概念:
服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端(而cookie是保存在浏览器的)的对象中。HttpSession
2. 快速入门:
- 获取HttpSession对象:
HttpSession session = request.getSession(); - 使用HttpSession对象:
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
新建两个servlet:
Servletsessiondemo1:
package cn.itcast.session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @author QLBF
* @version 1.0
* @date 2020/11/25 11:03
*/
@WebServlet("/Servletsessiondemo1")
public class Servletsessiondemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用session共享数据
//1.获取session
HttpSession session = request.getSession();
//2.存储数据
session.setAttribute("msg1","hello Session!");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
Servletsessiondemo2:
package cn.itcast.session;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @author QLBF
* @version 1.0
* @date 2020/11/25 11:03
*/
@WebServlet("/Servletsessiondemo2")
public class Servletsessiondemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用session获取数据
//1.获取session
HttpSession session = request.getSession();
//2.获取数据
Object msg1 = session.getAttribute("msg1");
System.out.println(msg1);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
先输入:
再输入:
控制台输出:
Servletsessiondemo2成功获取数据
3. 原理
- Session的实现是依赖于Cookie的。
4.与cookie的区别
session与Cookie的区别:
- session存储数据在服务器端,Cookie在客户端
- session没有数据大小限制,Cookie有
- session数据安全,Cookie相对于不安全
cookie:浏览器访问A资源,A资源里面会发送一个cookie并相应给浏览器,当浏览器再访问B资源时,会携带cookie头过去,那么B资源就可以用request来获取这个cookie了。
session:当浏览器访问A资源时,A资源会创建一个session,并设定了值。当浏览器访问B资源时,可以直接获取A资源的值。(其实也是通过cookie实现的,但写代码的步骤就是这样)
Session一般和重定向(因为是两次请求)一起用,请求转发自己弄就行不需要session。