Session variable created in a servlet. How to pass it to a .jsp page?

I’m new to Java and have been struggling with a problem for couple of days. I’m trying to implement a user login system for a website. This is how I’ve been trying to do it:

User fills in his/her user name and password, then clicks submit. The form data is passed (via the action-attribute in the form) to a servlet, that stores the name and the password in variables and does some database interaction.

Then, I tried to create a new session (HttpSession) and store the name and the password: for example

session.setAttribute("attributeNameHere", attributeValueHere);

I can access these values in the servlet without a problem. So the servlet remembers the session.

My question is: How can I pass this newly created session to a .jsp page so that the .jsp page can access the session created in the servlet? I’ve tried response.sendRedirect etc., but the .jsp page does not remember the values set (output is null).

Is there a better way to achieve the same result (process login in a servlet, create a session, pass the session to some .jsp page that can check if the values are still set [the user is still logged in])?

Links to good tutorials are also appreciated.

a servlet session is totally different than a browser session (jsp), so you need to directly pass info directly between servlet and browser, many ways to do…

You’re close. After you’ve set the values to session like you posted above. You call the sendRedirect method to your next jsp page. Inside the jsp page, you get the session values out and set them to strings.


String str = (String)session.getAttribute("attributeNameHere");

If you’re getting null for str. Be 100% sure that you are setting the attributeNameHere string to something in the servlet before putting it to session.

Chris is right there. You can also further ensure it works if cookies are not enabled by doing this when redirecting:


String redirect = response.encodeRedirectURL(request.getContextPath() + url );
response.sendRedirect(redirect);

The idea there is simply to encode the user’s session into the URL (only when cookies are not enabled).

Thank you for your help everyone!