Session用于跟踪客户的状态。Session指的是在一段时间内,单个客户与web服务器的一连串相关的交互过程。在一个Session中,客户可能会多次请求访问同一个网页,也有可能请求访问各种不同的服务器资源
数据库存储的一些商品
create table t_goods
(
gid int primary key auto_increment,
gname varchar(20),
price double,
mark varchar(100)
);
insert into t_goods(gname,price,mark) values('泡面',4.5,'够香够辣就是这个味!');
insert into t_goods(gname,price,mark) values('火腿',8.5,'肉质细腻Q弹!');
insert into t_goods(gname,price,mark) values('雪碧',3.5,'清爽冰凉随心爽!');
select * from t_goods;
我们在登录页面使用Session方法 在登陆同时查询商品列表
因此我们把商品信息传输到页面中进行展示---可以使用Session方法
HttpSession session=req.getSession();
把查询到商品信息集合存储到session对象中,起名字叫做goodList
session.setAttribute("goodsList",goodsList);
@WebServlet("/ServletGoodsAll")
public class ServletGoodsAll extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码格式
req.setCharacterEncoding("utf-8");//请求编码
resp.setCharacterEncoding("utf-8");//响应编码
//去查询数据库中商品信息表中的数据
GoodsDaolmpl goodsDaolmpl=new GoodsDaolmpl();
List<Goods> goodsList=goodsDaolmpl.selectAll();
System.out.println(goodsList);
HttpSession session=req.getSession();//获取HttpSession
session.setAttribute("goodsList",goodsList);
resp.sendRedirect("cg.jsp");
}
使用查询成功的jsp页面获取Session
获取session对象
HttpSession session2=request.getSession();
从session对象中获得集合
List<Goods> goodsList=(List<Goods>) session2.getAttribute("goodsList");
这里我们需要使用for循环让他们一条条输出出来
for (Goods goods : goodsList){}
调用实体类
<tr>
<td><%=goods.getGid()%></td>
<td><%=goods.getGname()%></td>
<td><%=goods.getPrice()%></td>
<td><%=goods.getMark()%></td>
</tr>
我们可以使用EL表达式通过 ${} 从作用域对象中自动获取数据,如果是对象可以通过,访问其属性
目的是为了获取{}中指定的对象(参数、对象等)的值
如:
${user.name}<====>User user = (User)request(搜寻范围).getAttribute(user);
String name = user.getName();
out.println(name);
从当前页面起开始搜寻 user对象,然后获取该对象的name属性值
其搜寻的范围依次是:session
如果未搜索到,即会返回null值
<h3>欢迎${user.username}来到主页</h3>
<table>
<tr>
<th>商品编号</th>
<th>商品名称</th>
<th>商品价格</th>
<th>商品说明</th>
</tr>
<%
//获取session对象
HttpSession session2=request.getSession();
//从session对象中获得集合
List<Goods> goodsList=(List<Goods>) session2.getAttribute("goodsList");
for (Goods goods : goodsList){
%>
<tr>
<td><%=goods.getGid()%></td>
<td><%=goods.getGname()%></td>
<td><%=goods.getPrice()%></td>
<td><%=goods.getMark()%></td>
</tr>
<%
}
%>
</table>
最后的结果