JSP中请求和会话范围的区别?

时间:2016-05-20 08:17:26

标签: html jsp

有人可以解释JSP页面中会话和请求范围之间的区别吗?

1 个答案:

答案 0 :(得分:0)

请将以下JSP复制并粘贴到您的网络应用中。使用浏览器的刷新按钮和页面上的刷新链接随机刷新页面。您将看到会话范围提供了一个存储用户数据的位置,无需任何工作即可访问您的Web应用程序。请求参数仅保存当前请求的数据。为了使用请求参数来保存数据,我们必须将它来回发送到服务器。

${pageContext.session.setAttribute("count", count + 1)} 
If you refresh this page using your browser's refresh button, <br/> 
then you will increment the session-scoped variable "count" but not the request parameter "r".<br/> 
<a href="${pageContext.request.requestURL}?r=${param.r + 1}">
    Click here to refresh this page and increment the r parameter.
</a><br/>
If you use the above link to refresh this page, <br/> 
then you increment the r parameter by sending a new value in the query string. <br/> 
This page has been requested ${count} times in this session. <br/> 
The value of the r parameter in the current request is ${param.r eq null? "null" : param.r}    

如果您使用的是旧服务器,则必须使用scriptlet。

<%
    Integer count = (Integer)session.getAttribute("count");
    if(count==null)count = new Integer(0);
    session.setAttribute("count",new Integer(count.intValue() + 1)); 
%>
If you refresh this page using your browser's refresh button, <br/> 
then you will increment the session-scoped variable "count" but not the request parameter "r".<br/> 
<a href="${pageContext.request.requestURL}?r=${param.r + 1}">
    Click here to refresh this page and increment the r parameter.
</a><br/>
If you use the above link to refresh this page, <br/> 
then you increment the r parameter by sending a new value in the query string. <br/> 
This page has been requested ${count} times in this session. <br/> 
The value of the r parameter in the current request is ${param.r eq null? "null" : param.r}    

可以在页面上创建请求范围的变量,并访问页面上的其他位置。如果请求被转发到另一个页面,那么该页面上的变量也可用。

${pageContext.request.setAttribute("message", "hello")} 
${message}