1.概念
Session:服务端会话跟踪技术:将数据保存到服务端。
HttpSession session = request.getSession();
void setAttribute(String name,Object o)
Object getAttribute(String name)
void removeAttribute(String name)
介绍完Session相关的API后,接下来通过一个案例来完成对Session的使用,具体实现步骤为:
1)创建名为SessionDemo1的Servlet类
@WebServlet("/demo1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
2)创建名为SessionDemo2的Servlet类
@WebServlet("/demo2")
public class SessionDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
3)SessionDemo1:获取Session对象、存储数据
@WebServlet("/demo1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//存储到Session中
//1. 获取Session对象
HttpSession session = request.getSession();
//2. 存储数据
session.setAttribute("username","zs");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
(4)SessionDemo2:获取Session对象、获取数据
@WebServlet("/demo2")
public class SessionDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取数据,从session中
//1. 获取Session对象
HttpSession session = request.getSession();
//2. 获取数据
Object username = session.getAttribute("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
(5)启动测试,
http://localhost:8080/cookie-demo/demo1
,将数据存入Sessionhttp://localhost:8080/cookie-demo/demo2
,从Session中获取数据
通过案例的效果,能看到Session是能够在一次会话中两次请求之间共享数据。
小结
至此Session的基本使用就已经完成了,重点要掌握的是:
Session的获取
HttpSession session = request.getSession();
Session常用方法的使用
void setAttribute(String name, Object o)
Object getAttribute(String name)
**注意:**Session中可以存储的是一个Object类型的数据,也就是说Session中可以存储任意数据类型。
介绍完Session的基本使用之后,那么Session的底层到底是如何实现一次会话两次请求之间的数据共享呢?