开发者

Access JSP Context inside custom EL function

How can I access开发者_如何学编程 the JSP context inside a custom EL function.


You have to explicitly include it as an argument to the method that implements your EL function.

Java method that implements EL function:

public static Object findAttribute(String name, PageContext context) {
    return context.findAttribute(name);
}

TLD entry for EL function:

<function>
    <name>findAttribute</name>
    <function-class>kschneid.Functions</function-class>
    <function-signature>java.lang.Object findAttribute(java.lang.String, javax.servlet.jsp.PageContext)</function-signature>
</function>

Usage in JSP:

<%@ taglib prefix="kfn" uri="http://kschneid.com/jsp/functions" %>
...
<c:if test="${empty kfn:findAttribute('userId', pageContext)}">...</c:if>


Or you can use a sophisticated trick. If you are OK with the ServletContext rather than PageContext it will be much easier

  • In your EL function class, define a static ThreadLocal<PageContext> variable
  • From a custom filter, set that PageContext
  • Access freely from your EL function

Code example:

public class MyFunctions {

    private static final ThreadLocal<ServletContext> servletContext = new ThreadLocal<>();

    public static void setServletContext(ServletContext servletContext) {
        MyFunctions.servletContext.set(servletContext);
    }

}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
    ...

    MyFunctions.setServletContext(servletRequest.getServletContext());

    filterChain.doFilter(servletRequest, servletResponse);
}

If you really need PageContext better do that setPageContext in a JSP scritplet, possibly in an inclusion file. This has the drawback that EVERY JSP file must perform that inclusion

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜