views:

22

answers:

1

So I'm using a bean on a JSP page to store some data, like so:

<jsp:useBean id="data" class="myclass" scope="session" />

Is there anyway to access this bean from a servlet at a later time in the same session?

EDIT:

Apparently I'm not accessing the same session when I load the jsp page and the servlet. I'm printing out the session ID and it's giving me a different value for both pages, so I can't access the bean. Any ideas?

+1  A: 

Yes, you can obtain it as attribute from the session by the id as key.

Data data = (Data) request.getSession().getAttribute("data");

Note that you need to put classes in a package, else you cannot import it. You'd also like to give it a more sensible name than myclass.

BalusC
It was just an example, not my actual code, but thanks!
garsh0p
You're welcome.
BalusC
Apparently I'm not accessing the same session when I load the jsp page and the servlet. I'm printing out the session ID and it's giving me a different value for both pages, so I can't access the bean. Any ideas?
garsh0p
Sessions are domain and context dependent. If the servlet listens on an URL of a different domain and/or context than the JSP, then it will indeed use a different session. You can however let different contexts share the same session by configuring the servletcontainer accordingly (in Tomcat, set `emptySessionPath` attribute of `<Connector>` to `true`). But you cannot share sessions among different domains due to security restrictions in HTTP spec.
BalusC