JEXL是一個表達式語言的解析引擎,用來解析表達式,被用來做一個條件判斷,數據有效性校驗,工作流等場合,一個示例如下:

 

Java代碼  

JAXBContext解析Timestamp_字符串


1. private static HashMap<String, Object> contextMap = new HashMap<String, Object>();  
2.   
3. @Before  
4. public void init() {  
5. "str", "字符串");  
6. "index", 12);  
7. "map", new HashMap<String, Object>() {  
8.             {  
9. this.put("key1", "value1");  
10.             }  
11.         });  
12.     }

 

首先有一些基礎數據:通過這些基礎數據計算一些表達式的示例如下:

Java代碼  

JAXBContext解析Timestamp_模板引擎_02


1. @Test  
2. public void testJexl() throws Exception {  
3.   
4. new String[] { "12+3", "str", "index",  
5. "index+5", "map.key1" };  
6.         JexlContext jexlContext = JexlHelper.createContext();  
7.         jexlContext.setVars(contextMap);  
8. for (String expression : expressions) {  
9.             Expression expr = ExpressionFactory.createExpression(expression);  
10.             Object obj = expr.evaluate(jexlContext);  
11. "  =>  " + obj);  
12.         }  
13.     }


該程序的運行結果為:

Java代碼  

JAXBContext解析Timestamp_字符串_03

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

    freemarker之類的模板引擎來計算格子的值的,但是由於會用到一些複雜的運算,如三元表達式等,freemarker顯得有點不能勝任,所以還是考慮用jexl實現模板引擎的功能,仍然以上面的基礎數據為例,期望以下的表達式輸出結果:

     

    Txt代碼  

    JAXBContext解析Timestamp_模板引擎_04


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

     

    EL表達式${},如果包含就調用JEXL引擎去解析該表達式,從而實現一個利用JEXL解析的模板引擎,從期望的結果可以看出,該模板引擎支持簡單的表達式解析和嵌套表達式解析功能。