Servlet中的Session使用方法


Servlet中的doGet方法:

 1 protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
 2         request.setCharacterEncoding("utf-8");
 3         response.setContentType("text/html;charset=utf-8");
 4         // 調用 HttpServletRequest 的公共方法 getSession() 來獲取 HttpSession 對象,如果沒有,則創建一個
 5         HttpSession session = request.getSession();
 6         // 返回session對象中與指定名稱綁定的對象,如果不存在則返回null(記得將返回后的Object類型轉換為對象原本的類型)
 7         Integer accessedCount = (Integer)session.getAttribute("accessedCount");
 8         if (accessedCount == null) {
 9             accessedCount = new Integer(0);
10             session.setAttribute("accessedCount", accessedCount);
11         }
12 
13         PrintWriter out = response.getWriter();
14         out.print("創建session成功");
15     }

使用Servlet中的request對象獲取session對象並輸出其屬性:

 1 HttpSession session = request.getSession();
 2         Integer accessedCount = (Integer)session.getAttribute("accessedCount");
 3         if (accessedCount == null) {
 4             accessedCount = new Integer(0);
 5         } else {
 6             accessedCount = new Integer(accessedCount.intValue()+1);
 7         }
 8         // 每次更新對象的值都需要重新設置session中的屬性
 9         session.setAttribute("accessedCount", accessedCount);
10 
11         PrintWriter out = response.getWriter();
12         out.print("sessionId: " + session.getId() + "<br />");
13         out.print("sessionCreationTime: " + new Date(session.getCreationTime()) + "<br />");
14         out.print("sessionLastAccessedTime: " + new Date(session.getLastAccessedTime()) + "<br />");
15         out.print("被訪問的次數: " + session.getAttribute("accessedCount") + "<br />");

 遇到的疑惑(已解決):

1、Integer對象並不能直接改變值,只能新分配一個對象。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM