JEXL实现模板引擎的功能

JEXL是一个表达式语言的解析引擎,用来解析表达式,被用来做一个条件判断,数据有效性校验,工作流等场合,一个示例如下:

private static HashMap<String, Object> contextMap = new HashMap<String, Object>();

	@Before
	public void init() {
		contextMap.put("str", "字符串");
		contextMap.put("index", 12);
		contextMap.put("map", new HashMap<String, Object>() {
			{
				this.put("key1", "value1");
			}
		});
	}

 

首先有一些基础数据:通过这些基础数据计算一些表达式的示例如下:

@Test
	public void testJexl() throws Exception {

		String[] expressions = new String[] { "12+3", "str", "index",
				"index+5", "map.key1" };
		JexlContext jexlContext = JexlHelper.createContext();
		jexlContext.setVars(contextMap);
		for (String expression : expressions) {
			Expression expr = ExpressionFactory.createExpression(expression);
			Object obj = expr.evaluate(jexlContext);
			System.out.println(expression + "  =>  " + obj);
		}
	}

 

该程序的运行结果为:

12+3  =>  15
str  =>  字符串
index  =>  12
index+5  =>  17
map.key1  =>  value1

 

    但是在一些稍微复杂的场合,除了表达式本身,还有一些其他的数据,或者无法区分一个字符串是否为表达式的情况,比如制作的数据导出模板,有一些单元格是需要通过表达式取值的,而另外一些单元格就是纯粹的文本,这就没有直接通过表达式引擎对这些格子计算值了,在这样的场景下,其实是应该应用freemarker之类的模板引擎来计算格子的值的,但是由于会用到一些复杂的运算,如三元表达式等,freemarker显得有点不能胜任,所以还是考虑用jexl实现模板引擎的功能,仍然以上面的基础数据为例,期望以下的表达式输出结果:

1+2=${1+2}  =>  1+2=3
str is ${str}  =>  str is 字符串
index is ${index}  =>  index is 12
index+5 is ${index+5}  =>  index+5 is 17
map.key1 is ${map.key1}  =>  map.key1 is value1
inner expression ${index+${index+${index}} + ${index}}  =>  inner expression 48

 

    即,通过解析字符串中是否包含EL表达式${},如果包含就调用JEXL引擎去解析该表达式,从而实现一个利用JEXL解析的模板引擎,从期望的结果可以看出,该模板引擎支持简单的表达式解析和嵌套表达式解析功能。

   整个测试类代码及解析类代码见附件.

你可能感兴趣的:(模板引擎,JEXL)