How to evaluate a JSP EL expression inside a servlet

I’d like to leverage the JSP Expression Language to evaluate JSP EL expressions inside a servlet.
Ideally, I’d like to use the exact same ExpressionFactory and context used in JSPs, in order to get access to the usual JSP EL variables such as ${param.myParam} or ${cookie.myCookie}.

So far I came up with the following :

package test;

import java.io.IOException;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.StandardELContext;
import javax.el.ValueExpression;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspApplicationContext;
import javax.servlet.jsp.JspFactory;

@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("text/plain;charset=UTF-8");
        ServletContext svc = getServletContext();
        JspFactory jspf = JspFactory.getDefaultFactory();
        JspApplicationContext jspContext = jspf.getJspApplicationContext(svc);
        ExpressionFactory expressionFactory = jspContext.getExpressionFactory();
        ELContext context = new StandardELContext(expressionFactory);
        ValueExpression expression = expressionFactory.createValueExpression(context, "hello ${param.x}", Object.class);
        response.getWriter().println(expression.getValue(context));
    }

}

which fails with:

ELResolver cannot handle a null base Object with identifier 'param'

The issue seems to lie in finding the proper ELContext.


Source: jsp

Leave a Reply