如何评估servlet中的JSP EL表达式

时间:2015-05-15 15:21:24

标签: jsp servlets el

我想利用JSP表达式语言来评估servlet中的JSP EL表达式。 理想情况下,我想使用JSP中使用的完全相同的ExpressionFactory和上下文,以便访问常见的JSP EL变量,例如$ {param.myParam}或$ {cookie.myCookie}。

到目前为止,我想出了以下内容:

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));
    }

}

失败了:

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

问题似乎在于找到合适的ELContext。

1 个答案:

答案 0 :(得分:0)

您是否需要在上下文中添加ImplicitObjectELResolver

StandardELContext context = new StandardELContext(expressionFactory);
context.addELResolver(new javax.servlet.jsp.el.ImplicitObjectELResolver());

更新

我添加了以下内容以使其正常工作(您可能需要更改一些参数)

context.putContext(JspContext.class, jspf.getPageContext(this /*the current servlet*/, request, response, "/error", false, 8192, false));