在没有Servlet容器的情况下评估JSP EL

时间:2011-06-29 21:53:24

标签: unit-testing jsp el

这就是我想要做的事情:

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

这可能吗?

2 个答案:

答案 0 :(得分:1)

是和否。 EL是JSP的一个组成部分,JSP编译器实际上会在JSP文件中生成Servlet等生成的大量内容。在一天结束时,调用ExpressionFactory上的方法,您可以做同样的事情来评估您的EL表达式(在设置适当的ELContext之后)。

使用String.format可能会更好,但有可能......

答案 1 :(得分:1)

是的,有可能,您可以参考此link以获取更多信息。如您所见,为了独立使用EL表达式,您必须实现多个类,例如javax.el.ELContext。我发现JUEL,它是EL表达式的一个实现,已经在de.odysseus.el.util包中提供了这些类的非常好的实现。

我玩过JUEL。这是我的测试代码供你参考:

/*
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));