I am trying to figure out how to use sessions using JSTL, so I began by trying to set a session attribute in a Jsp and passing that attribute to another Jsp within the same application and retrieving it there.

I set the attribute and used the dispatcher to get to the other servlet, in another attempt I used sendRedirect to forward the request to the other servlet.

Here is the first Jsp (where I set the attribute):

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<body>

<c:set var="session" scope="session" value="test"></c:set>
<%
response.sendRedirect("session.jsp"); // I know I could use the JSTL tag forward
%>

</body>
</html>

In the other Jsp ("session.jsp"):

<%

HttpSession s = request.getSession();
if(s.isNew())
    out.print("new session " );

out.print(s.getAttribute("session"));  
%>

When I use sendRedirect the result is "test", meaning that the session wasn't newly created. However, when I use forward (dispatcher) the result is "new session test".

I don't know the reason for such behavior, although it would make sense if the results were reversed.

有帮助吗?

解决方案

when you use redirect the server says to client (user browser) that please send a new request for me. then user browser request new page. in this state we have 2 request. see following picture:

enter image description here

but forward request occured in the server. if you have n time forward a request it back one request. see following picture:

enter image description here

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top