Search code examples
jspservletsusebean

How to get instance created by <jsp:useBean scope="session"> in a servlet


I have a JSP with the following <jsp:useBean>:

<jsp:useBean id="res" class="mycompany.Resource" scope="session" />

I would like to get the instance from the session in a servlet. How can I achieve this?


Solution

  • It's stored as a session attribute under the key as specified by <jsp:useBean id>. You can get it by HttpSession#getAttribute() passing the key as follows:

    Resource resource = (Resource) request.getSession().getAttribute("res");
    // ...