使用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)

浙公网安备 33010602011771号