2015-05-15 84 views
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。

回答

0

您是否需要將ImplicitObjectELResolver添加到您的上下文中?

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

UPDATE

添加以下得到它的工作(你可能需要改變某些參數)

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

謝謝,我甚至不知道這樣一類的存在。這無疑是正確的軌道上,但是這失敗: 顯示java.lang.NullPointerException 在javax.servlet.jsp.el.ImplicitObjectELResolver $ ImplicitObjects.getImplicitObjects(ImplicitObjectELResolver.java:612) 一些更神奇似乎​​有需要以便ImplicitObjectELResolver訪問隱式對象。 – Remi

+0

我改編了我的答案 –

+0

很好,這個作品,感謝魔術! – Remi