JSP 中的请求属性和 pagecontext 属性
request attribute and pagecontext attribute in JSP
我遇到过在操作中设置我的属性的场景 class:
request.setAttribute("itemList", itemList); /* valid List item - confirmed */
和 JSP,我尝试在 forEach
标签内使用它作为
<c:forEach items="${itemList}" var="individualItem">
<!-- rest of the code -->
评估为空项。但是我在这个标签之前添加了一个小脚本:
<% List<MyItem> itemList = (List<MyItem>)request.getAttribute("itemList"); // evaluates as my valid item list
List<MyItem> itemList = (List<MyItem>)pageContext.getSession().getAttribute("itemList"); // evaluates as NULL
%>
这是否意味着我最好在前端使用 pageContext 或 session 属性而不是请求属性?或者有规定吗?
韩国,
规则:
这取决于您的要求,Session 在整个会话期间(即直到用户关闭浏览器或会话超时)保留数据(即变量值),而 Request 在单个请求中保留数据,这包括重定向或分派请求时的情况。
在您的示例中,pageContext.getSession().getAttribute("itemList") returns null 因为您在请求中设置的属性不是会话,但为什么 EL 代码 returns null,我不明白为什么.....可能是你在你的 jsp 中定义了一个名为 'itemList' 的局部变量,它是 null ,所以它首先读取它,检查answer here
我遇到过在操作中设置我的属性的场景 class:
request.setAttribute("itemList", itemList); /* valid List item - confirmed */
和 JSP,我尝试在 forEach
标签内使用它作为
<c:forEach items="${itemList}" var="individualItem">
<!-- rest of the code -->
评估为空项。但是我在这个标签之前添加了一个小脚本:
<% List<MyItem> itemList = (List<MyItem>)request.getAttribute("itemList"); // evaluates as my valid item list
List<MyItem> itemList = (List<MyItem>)pageContext.getSession().getAttribute("itemList"); // evaluates as NULL
%>
这是否意味着我最好在前端使用 pageContext 或 session 属性而不是请求属性?或者有规定吗?
韩国,
规则:
这取决于您的要求,Session 在整个会话期间(即直到用户关闭浏览器或会话超时)保留数据(即变量值),而 Request 在单个请求中保留数据,这包括重定向或分派请求时的情况。
在您的示例中,pageContext.getSession().getAttribute("itemList") returns null 因为您在请求中设置的属性不是会话,但为什么 EL 代码 returns null,我不明白为什么.....可能是你在你的 jsp 中定义了一个名为 'itemList' 的局部变量,它是 null ,所以它首先读取它,检查answer here