【问题标题】:How to evaluate a JSP EL expression inside a servlet如何在 servlet 中评估 JSP EL 表达式
【发布时间】:2015-05-15 15:21:24
【问题描述】:

我想利用 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。

【问题讨论】:

    标签: jsp servlets el


    【解决方案1】:

    您不需要在上下文中添加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));
    

    【讨论】:

    • 谢谢,我什至不知道有这样的课程。这肯定是在正确的轨道上,但是这失败了: java.lang.NullPointerException at javax.servlet.jsp.el.ImplicitObjectELResolver$ImplicitObjects.getImplicitObjects(ImplicitObjectELResolver.java:612) 为了实现ImplicitObjectELResolver 来访问隐式对象。
    猜你喜欢
    • 2016-07-10
    • 2014-06-21
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2016-05-08
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多