JSP :: Confused with session objects

I just started learning Java Servlets and JSP, and got a little confused in the session object. Inside the servlet, I have this:

public class SampleServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException {

        HttpSession session = request.getSession(true);
        session.setAttribute("_session", "_value");
                response.sendRedirect("page2.jsp");         
        }
}

Now, inside page2.jsp, there is also a session object, but when I do this

<%
out.print(session.getAttribute("_session"))
%>

it doesn't seem to get the value (as if it was not set). I tried to set the boolean attribute to true, but on the jsp page it returns false. Can someone tell me the correct way to do this? As for what I'm trying to do, I want to share some session variables.

+3
source share
3 answers

Use request.getRequestDispatcher (). forward () instead of response.sendRedirect ();

, :

 HttpSession session = request.getSession(true);
 session.setAttribute("_session", "_value");
 request.getRequestDispatcher("page2.jsp").forward();     

, response.sendRedirect() , , jsp . request.forward() .

. http://www.coderanch.com/t/170618/java-Web-Component-SCWCD/certification/sendRedirect-Vs-requestdispatcher-forward

+4

, , EL!

Java:

HttpSession session  = request.getSession(true);
session.setAttribute("foo", "bar");

JSP:

<html>
    ...
    <body>
        ...
        <p>${foo}</p>
        ...
    </body>
</html>

, bar.

+1

( EL ${_session}, ), . - . , , , ? ? ? , / , . , cookie, cookie? HttpServletResponse#encodeRedirectURL(), URL- .

response.sendRedirect(response.encodeRedirectURL("page2.jsp"));

: , , :

System.out.println("Session ID: " + session.getId());

JSP:

<p>Session ID: ${pageContext.session.id}</p>

HTTP, Firebug < i2 > . HTTP- Set-Cookie , HTTP- Cookie / cookie, JSESSIONID , , .


2:, , , , , Tomcat 6 Glassfish 3, . , Appengine, cookie .

As proof, here is a screen that proves that Glassfish sets a cookie with Set-Cookie and , by triggering a redirect to Location:

alt text

+1
source

Source: https://habr.com/ru/post/1750188/


All Articles