文章目录
16.11 会话技术_Session_快速入门
-
Session:服务器端会话技术,在一次会话的多次请求间共享数据,将数据保存在服务器端的对象中(HttpSession)。
-
快速入门:
-
1. 获取 HttpSession对象:
HttpSession session = request.getSession();
-
2. 使用 HttpSession对象:
Object getAttribute(String name)
void setAttribute(String name, Object value)
void removeAttribute(String name)
- 示例:
package com.xww.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;
@WebServlet("/sessionDemo1")
public class SessionDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用session共享数据
//1.获取session
HttpSession session = request.getSession();
//2.存储数据
session.setAttribute("name","xww");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
package com.xww.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;
@WebServlet("/sessionDemo2")
public class SessionDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//使用session获取数据
//1.获取session
HttpSession session = request.getSession();
//2.获取数据
Object name = session.getAttribute("name");
System.out.println(name);//xww
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
16.12 会话技术_Session_原理分析
- Session的实现是依赖于Cookie的。
-
图示: