0
我想利用JSP表達式語言來評估servlet中的JSP EL表達式。 理想情況下,我想使用與JSP中使用的完全相同的ExpressionFactory和上下文,以便訪問常見的JSP EL變量,如$ {param.myParam}或$ {cookie.myCookie}。如何評估servlet中的JSP EL表達式
到目前爲止,我想出了以下內容:
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。
謝謝,我甚至不知道這樣一類的存在。這無疑是正確的軌道上,但是這失敗: 顯示java.lang.NullPointerException 在javax.servlet.jsp.el.ImplicitObjectELResolver $ ImplicitObjects.getImplicitObjects(ImplicitObjectELResolver.java:612) 一些更神奇似乎有需要以便ImplicitObjectELResolver訪問隱式對象。 – Remi
我改編了我的答案 –
很好,這個作品,感謝魔術! – Remi