How can I access a session scope bean in a servlet?

I create a java bean in the session scope using <jsp:useBean> in a JSP page. I then need to access the information held by the bean in a servlet. How can I get hold of the bean in the servlet?
Answer:
The JSP session scope corresponds to the javax.servlet.http.HttpSession class in the Servlet API. The session scope objects are saved as attributes for the current instance of this class, so you can get them with code like this in a servlet:

HttpSession session = request.getSession();
String foo = (String) session.getAttribute("foo");

For more information about how to share objects between JSP pages and servlets, see Chapter 14 in the book.

One thought on “How can I access a session scope bean in a servlet?

  1. Very useful and interesting. Thankyou for sharing this Great article

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>