- 為什么要使用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相對于不安全