使用session存儲數據


@WebServlet("/reply")
public class ReplyServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //設置編碼
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //創建session對象
        HttpSession session = req.getSession();
        List<Reply> list = (List<Reply>) session.getAttribute("list");

        //判斷session中有沒有數據  有的話直接跳轉  沒的話查數據庫
        if (list==null){
            //連接業務層

            QuaryServiceImp quaryServiceImp = new QuaryServiceImp();
            List<Reply> replies = quaryServiceImp.quaryAll();
            session.setAttribute("list", replies);

        }
        resp.sendRedirect("reply.jsp");

    }
}

  

<%@ page import="java.util.List" %>
<%@ page import="com.bjsxt.entiy.Reply" %><%--
  Created by IntelliJ IDEA.
  User: 60590
  Date: 2019/11/28
  Time: 19:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href=<%= request.getContextPath()%>/>
    <script src="jq/jquery-1.9.1.js"></script>
    <script>
        $(function () {
            $("td:even").css("background","pink");
        })
    </script>
</head>
<body>
<%
    HttpSession session1 = request.getSession();
    List<Reply> list = (List<Reply>) session1.getAttribute("list");
%>
<table border="1px"width="50%">
    <tr>
        <th>評論編號</th>
        <th>帖子編號</th>
        <th>評論作者</th>
        <th>評論內容</th>
        <th>評論時間</th>
    </tr>
    <%
        for (Reply reply:list) {
     %>
    <tr>
        <td><%=reply.getReplyid()%></td>
        <td><%=reply.getTopicid()%></td>
        <td><%=reply.getAuthor()%>></td>
        <td><%=reply.getContent()%></td>
        <td><%=reply.getCreatedate()%></td>
    </tr>
    <%
        }
    %>
</table>
</body>
</html>

  

<%--
  Created by IntelliJ IDEA.
  User: 60590
  Date: 2019/11/28
  Time: 19:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href=<%= request.getContextPath()%>/>
</head>
<body>
<<a href="reply">點擊查詢全部帖子</a>
</body>
</html>

  

Cookie與Session的區別

共同點:同一用戶的不同請求的數據共享
區別: Cookie是客戶端的數據存儲技術,
Session是服務器端的數據存儲技術

cookie數據存放在客戶端,session數據放在服務器上(sessionid可以通過cookie保存在客戶端,也可以使用URL重寫方式)

•cookie不是很安全(可以加密),別人可以分析存放在本地的COOKIE並進行COOKIE欺騙,考慮到安全應當使用session

•session會在一定時間內保存在服務器上。當訪問增多,會比較占用你服務器的性能,考慮到減輕服務器性能方面,應當使用COOKIE

•單個cookie在客戶端的限制是3K,就是說一個站點在客戶端存放的COOKIE不能3K。
•Cookie的數據都以字符串的形式保存。Session中可以保存對象信息。

•典型使用
•Cookie:記住我 最近瀏覽商品 網頁皮膚
•session:登錄信息 購物車(也可以使用Cookie)

 

 


免責聲明!

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



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