Session
什么是session
- 服務器會給每個用戶(瀏覽器創建一個session物件)
- 一個session獨占一個瀏覽器,只要瀏覽器沒有關閉,這個session就存在
- 用戶登錄之后,整個網站它都可以訪問—>保存用戶的資訊 保存購物車的資訊
Session和cookie的區別:
- Cookie是把用戶的資料寫給用戶的瀏覽器,瀏覽器保存(可以保存多個)
- Session把用戶的資料寫到用戶獨占Session中,服務器保存(保存重要的資訊,減少瀏覽器的資源浪費)
- Session物件由服務器創建
使用場景:
- 保存一個登錄用戶的資訊
- 購物車資訊
- 在整個網站中經常會使用的資料,我們將他保存在session中
Session的原理:

案例:創建session
public class SessionDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解決亂碼問題
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//給session中存資料
session.setAttribute("name",new Person("王樂樂",1));
//獲取session的id
String sessionId = session.getId();
//判斷session是不是新創建
if (session.isNew()){
resp.getWriter().write("session創建成功,session的id為"+ sessionId);
}
else{
resp.getWriter().write("session在服務器中已經存在了,session的id為"+ sessionId);
}
//session的id是保存在cookie中的 做了以下的操作
//session是肯定在服務端的記憶體中,只不過系統會將session id傳到客戶端并存在cookie中,下次你request到服務端時session id也一同被傳回服務端,服務端通過這個id到快取中找到對應的session,
//關閉瀏覽器是不會把服務端的快取session和客戶端cookie里存的session id洗掉的,session和cookie都有個有效期,過了有效期它會自動被清除,
// Cookie cookie = new Cookie("JSESSIONID",sessionId);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
獲取session
public class SessionDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解決亂碼問題
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
Person name =(Person) session.getAttribute("name");
resp.getWriter().write(name.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手動呼叫銷毀session
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
自動呼叫 會話過期 web.xml配置
<!-- 設定Session默認失效時間-->
<session-config>
<!-- 1分鐘后Session自動失效 以分鐘為單位-->
<session-timeout>1</session-timeout>
</session-config>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/276209.html
標籤:其他
上一篇:十、JavaScript 基礎
下一篇:CSS快速入門及優勢(前端基礎)
