- 為什么要使用Session?
- 怎樣使用Session?
- Session和Cookie的區(qū)別?
1.為什么要使用Session?
Session屬于服務(wù)器端存儲數(shù)據(jù),不限制存儲的內(nèi)容,任意類型均可存儲。
2.怎樣使用Session?
2.1 Session常用方法
| 用法 | 說明 |
|---|---|
| HttpSession session = request.getSession() | 獲取HttpSession對象 |
| Object getAttribute(String name) | 使用HttpSession對象 |
| void setAttribute(String name, Object value) | 設(shè)置HttpSession對象 |
| void removeAttribute(String name) | 刪除HttpSession對象 |
2.2 Session完整示例
示例代碼
@WebServlet("/session1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession httpSession = req.getSession();
httpSession.setAttribute("msg","hello session");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
@WebServlet("/session2")
public class SessionDemo2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession httpSession = req.getSession();
System.out.println(httpSession.getAttribute("msg"));
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
效果展示

image.png
3. Session和Cookie的區(qū)別?
- session存儲數(shù)據(jù)在服務(wù)器端,Cookie在客戶端
- session沒有數(shù)據(jù)大小限制,Cookie有
- session數(shù)據(jù)安全,Cookie相對于不安全