Evaluating JSP EL without a Servlet container

杀马特。学长 韩版系。学妹 提交于 2020-03-05 03:53:18

问题


Here's what I want to do:

Map<String, Object> model = new Hashmap<String, Object>();
model.put("a", "abc");
model.put("b", new Hashmap<String, Object>());
model.get("b").put("c", "xyz");
String el = "A is ${a} and C is ${b.c}";
assertEquals(elEval(el, model), "A is abc and C is xyz");

Is this possible?


回答1:


Yes , it is possible , you can refer to this link for more information . As you can see , in order to use the EL expression standalone , you would have to implement several classes such as the javax.el.ELContext . I found JUEL , which is one of the implementation of the EL expression , already provides very nice implementations of these classes in the de.odysseus.el.util package.

I have played around with JUEL .Here is my testing code for your reference:

/*
ExpressionFactoryImpl should be the implementation of ExpressionFactory used by  your application server. 
For example , in tomcat 7.0 , it is org.apache.el.ExpressionFactoryImpl , which is inside the jasper-el.jar .
jasper-el.jar  is the implemenation of EL expression provided by tomcat  , el-api.jar is the API of EL expression (i.e. JSR-245)
*/
ExpressionFactory factory = new ExpressionFactoryImpl();

/*
SimpleContext is the utility classes from fuel 
*/
SimpleContext context = new SimpleContext();    

//Set the variables in the context  
Map<String,Object> hashMap =  new HashMap<String,Object>();
hashMap.put("c", "xyz");
context.setVariable("a", factory.createValueExpression("abc", String.class));   
context.setVariable("b", factory.createValueExpression(hashMap, HashMap.class));    

//Create the EL expression 
ValueExpression expr = factory.createValueExpression(context,  "A is ${a} and C is ${b.c}", String.class);  
System.out.println(expr.getValue(context));



回答2:


Yes and no. EL is an integral part of JSP and the JSP compiler will actually output a lot of stuff in the Servlet et generates from the JSP file. At the end of the day, the methods on ExpressionFactory are called, and you could do the same thing to evaluate your EL expression (after setting up an appropriate ELContext).

You would probably be better off using String.format, but it is possible...



来源:https://stackoverflow.com/questions/6527724/evaluating-jsp-el-without-a-servlet-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!