jspel

Access JavaBean object and pass argument to JSP using EL


I am trying to convert our legacy code into JSTL+EL in our application. I just wanted to know if there's a way to access a JavaBean object and methods with arguments in JSP using EL?

So here's the before and after code.

BEFORE:

  <HTML>
<jsp:useBean id="someBean" scope="session" class="package.className" />
<head>
</head>
<BODY>
<p>
<%= ((package.className)session.getAttribute("someBean")).getSomeDataFromBean(request,response) %>
</p>
</BODY>
</HTML>

Then here's what I want to achieve

  <HTML>
    <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
    <%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
    <body> 
       <p> 
         <c:out value="${package.className.getSomeDataFromBean(request,response)}"/> </p>
    </body>
    </HTML>

Note that the package class is just a Bean, not a servlet.


Solution

  • Keep using <jsp:useBean>. It was fine. By default the JSP managed bean is already available by its id in EL scope as follows:

    ${someBean}
    

    So, this should do:

    <c:out value="${someBean.getSomeDataFromBean(pageContext.request, pageContext.response)}" />
    

    Note that the HttpServletRequest and HttpServletResponse instances are only available via ${pageContext}.