1

Can somebody explain the difference between session and request scopes in a JSP page?

ravi saurav
  • 59
  • 1
  • 7

1 Answers1

0

Please copy and paste the following JSP into your web app. Randomly refresh the page using your browser's refresh button and the refresh link on the page. You will see that the session-scope provides a place to store user data throughout his visit to your web app without any work. Request parameters hold data only for the current request. In order to use a request parameter to hold data, we have to send it back and forth to the server.

${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}    

If you are using an old server, then you will have to use a 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}    

Request-scoped variables can be created on the page and accessed somewhere else on the page. If the request is forwarded to another page, then the variable is available on that page as well.

${pageContext.request.setAttribute("message", "hello")} 
${message}
rickz
  • 4,324
  • 2
  • 19
  • 30