概念 :
服务器端会话技术,在一次会话的动次请求间共享数据, 将数据保存在服务器端的对象中。HTTPSession
快速入门
创建两个Servlet对象SessionDemo1和SessionDemo2
SessionDemo1用来发送共享数据, SessionDemo2用来获取共享数据
SessionDemo1
@WebServlet("/sessionDemo1")
public class SessionDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用Session来共享数据
//获取Session
HttpSession session = request.getSession();
//存储数据
session.setAttribute("msg","hello session");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
SessionDemo2
@WebServlet("/sessionDemo2")
public class SessionDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用Session来获取数据
//获取Session
HttpSession session = request.getSession();
//存储数据
Object msg = session.getAttribute("msg");
System.out.println(msg);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
启动服务器,先访问SessionDemo1,再访问SessionDemo2, 控制台输出如下:
原理
session的实现是依赖于Cookie的
图片来源于黑马程序员…