2011-06-29 35 views
0

這裏評估JSP EL這就是我想做的事:沒有一個Servlet容器

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

這可能嗎?

回答

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)); 
+0

謝謝!這看起來就像我正在尋找的東西。 –

1

是的,沒有。 EL是JSP的一個組成部分,JSP編譯器實際上會在Servlet中輸出很多東西,並從JSP文件中生成這些東西。在一天結束時,調用ExpressionFactory上的方法,您可以做同樣的事情來評估您的EL表達式(在設置合適的ELContext後)。

你可能會更好使用String.format了,但是也有可能......

+0

謝謝,我這樣做單元測試JSP表達式這樣的String.format不幫助:) –

+0

在在這種情況下,最好通過JSP編譯器運行整個文件,加載類並對其進行測試。 Tomcat中的編譯器稱爲Jasper。您可以下載它並分別在文件上運行它。 –