Session attributes

Hi gurus,

I hope this is a quick answer. I have a class which stores some variables eg. userName. When logging in, the servlet sets the following object:

request.setAttribute(“person”, myfields);

This can be accessed in the JSP with:

${person.userName}

However, when I try to pass that same object as a session attribute:

session.setAttribute(“person”, myfields);

${person.userName} no longer works. Any ideas why? My understanding is that EL treats request and session scoped variables the same way. Thx in advance…

Nevermind… I figured it out :slight_smile:

${sessionScope.person.userName}

You may or may not care about you can access session scope as

${person.userName}

Only if you didn’t store that in your request scope.

your JSP container looks into request -> session -> application scope. This is why you’re getting request scope’s person and not from session. I rarely had to specify the scope.

But I don’t have the “person” object stored anywhere in the request scope…I only initiated it once, when I was switching from request.setAttribute to session.setAttribute noted in the OP. Unless I specify the scope it will give me no output… :confused:

where are you setting the attributes? from Servlet or JSP? from your syntax, it looks to be JSP…which is a…“No! No!”

They are being set in the servlet.

after setting the attribute, I call:

RequestDispatcher view = getServletContext().getRequestDispatcher(“/welcome”);
view.forward(request, response);

Could there be a problem with that block perhaps?

This is very puzzling. I haven’t used the dispatcher class since school days. My wild programming sense tells me that your Session ID is being changed. Try to compare before and after Session ID. If it’s different than you know why your session is being lost. Another way of testing your session is to use redirect method. But in theory, forward should definitely work! and your session should contain that instance.

Okay, well now you got me curious :smiley: In a MVC structure how else can you redirect from servlet to JSP?

We use frameworks like spring or struts or java server faces that handle that type of code for us.

It is a pain in the ass to have to program the different forwards vs redirects and those frameworks move that type of work into configuration files. Using config files is tends to be less painful in the long run because if you need to change where a servlet (action, controller, etc…) redirects/forwards to, you won’t need to recompile your code.

Yup. My current flavor of MVC is Spring MVC/WebFlow. Later in June, I am taking a JSF 2.0 training course :D. Still, I’m pretty sure Spring Web is much better than JSF 2.0.