Access JSP context inside EL user function

How can I access the JSP context inside an EL user function.

+6
jsp el
source share
2 answers

You must explicitly include it as an argument in a method that implements your EL function.

Java method that implements the 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> 
+7
source share

Or you can use a difficult trick. If you are ok with ServletContext and not PageContext , it will be much easier

  • In your EL function class, set the static variable ThreadLocal<PageContext>
  • From a custom filter, set this PageContext parameter
  • Free access to 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 a PageContext , it is best to do this setPageContext in a JSP scritplet, possibly an include file. It has the disadvantage that EVERY JSP file must perform this inclusion

-one
source share

All Articles