简体   繁体   中英

Passing session attributes through forward and redirect

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:

在此处输入图片说明

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM