how to get an object and invoke a method in jstl EL in a JSP
I'm trying to convert the following scriptlet code to EL. I tried the following (below), but can't get it working. getValue() is a method off of ConfigFactory that returns a string:
In a listener, I set the configFactory as event.getServletContext().setAttribute("ConfigFactory", new ConfigFactory());
In my scriptlet code there is: (and it works fine)
<%
ConfigFactory cf = (ConfigFactory) application.getAttribute("ConfigFactory");
%>
Value from scriptlet= <%=cf.getValue()%> <br/>
开发者_StackOverflow
EL gives me trouble:
<c:set var="cf" value="${initParam['ConfigFactory']}"/>
<c:out value="${cf.getValue}"/> <!-- try # 1 -->
<c:out value="${cf.value}"/> <!-- try # 2 -->
This line
<c:set var="cf" value="${initParam['ConfigFactory']}"/>
does basically the same as
pageContext.setAttribute("cf", application.getInitParameter("ConfigFactory"));
You don't want this. Get rid of that line. In EL, you have implicitly direct access to all request, session and application attributes by just its name. The following
${ConfigFactory}
does basically the same as
out.print(pageContext.findAttribute("ConfigFactory"));
The PageContext#findAttribute()
tests respectively PageContext#getAttribute()
, HttpServletRequest#getAttribute()
, HttpSession#getAttribute()
and finally ServletContext#getAttribute()
until the first non-null value is been found. This is more what you want.
You can finally access the getValue()
method on it the usual EL way:
${ConfigFactory.value}
Not related to the problem, but you'd normally give instance identifiers a name starting with lowercase. You also don't do ConfigFactory ConfigFactory = new ConfigFactory();
, right? :)
Not tested:
${applicationScope.ConfigFactory.value}
精彩评论