J2EE--Session

  1. 為什么要使用Session?
  2. 怎樣使用Session?
  3. 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ū)別?

  1. session存儲數(shù)據(jù)在服務(wù)器端,Cookie在客戶端
  2. session沒有數(shù)據(jù)大小限制,Cookie有
  3. session數(shù)據(jù)安全,Cookie相對于不安全
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容