Java:如何在不实现接口的情况下评估 EL 表达式 - 独立(在任何 Web 框架之外)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17026863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: How to evaluate an EL expression - standalone (outside any web framework) without implementing interfaces?
提问by Ondra ?i?ka
I'd like to use EL in my application. But I can't find any howto. I usually end up needing some interface for which I don't have an implementation.
我想在我的应用程序中使用 EL。但我找不到任何方法。我通常最终需要一些我没有实现的接口。
I have a map of objects, and I want a string expression like Hello, ${person.name}
to be evaluated to a string.
我有一个对象映射,我想要像 Hello 这样的字符串表达式${person.name}
被评估为一个字符串。
How can I achieve that, using any of Commons EL, javax.el, OGNL, or such? Must be a standalone library.
如何使用 Commons EL、javax.el、OGNL 等实现这一点?必须是一个独立的库。
And I knowJava: using EL outside J2EE, and have seen JSTL/JSP EL (Expression Language) in a non JSP (standalone) context. That is not what I'm looking for.
而且我知道Java:在 J2EE 之外使用 EL,并且在非 JSP(独立)上下文中看到了JSTL/JSP EL(表达式语言)。那不是我要找的。
What I am looking for is an example of what dependency to add, and then how to initialize a parser which will have:
我正在寻找的是要添加什么依赖项的示例,然后是如何初始化将具有的解析器:
private static String evaluateEL( String expr, Map<String, String> properties );
and allow me to do:
并允许我做:
String greet = evaluateEL("Hello ${person.name}",
new HashMap(){{
put("person", new Person("Ondra"));
}}
);
And I need it to use some rational value, e.g. ""
on null
instead of throwing NPE or so.
我需要它来使用一些合理的价值,例如""
onnull
而不是抛出 NPE 左右。
回答by Ondra ?i?ka
There's quite a bunch of EL engines, of which most implement Java Expression Language API.
有相当多的 EL 引擎,其中大多数实现了 Java 表达式语言 API。
Commons EL (http://jakarta.apache.org/commons/el/) Implementation of the JSP EL API that's existed forever. This library can be found in many JSP containers (Tomcat for example) or used as a foundation for within many vendor's J2EE servers.
OGNL (http://commons.apache.org/proper/commons-ognl/) One of the most expressive ELs available today and widely used with WebWork (Struts 2) and Tapestry.
MVEL (https://github.com/mvel/mvel) A newcomer to EL which is part of the MVFlex/Valhalla project. Features look more in line with OGNL's offering with method invocation and some interesting regular expression support.
(Unified) Expression Language (https://jcp.org/aboutJava/communityprocess/final/jsr341/index.htmland http://jcp.org/en/jsr/detail?id=245) Standard expression language first introduced in Java EE 5 (EL 2.1) and enhanced in Java EE 6 (EL 2.2) and Java EE 7 (EL 3.0). Reference implementation available from Glassfish project - Unified Expression Language.
JEXL (http://jakarta.apache.org/commons/jexl/) An implementation based on Velocity's parser. Because of this, it acts more like a limited templating solution with things like method invocation.
Commons EL ( http://jakarta.apache.org/commons/el/) 永远存在的 JSP EL API 的实现。该库可以在许多 JSP 容器(例如 Tomcat)中找到,或者用作许多供应商的 J2EE 服务器的基础。
OGNL ( http://commons.apache.org/proper/commons-ognl/) 当今最具表现力的 EL 之一,广泛用于 WebWork (Struts 2) 和 Tapestry。
MVEL ( https://github.com/mvel/mvel) EL 的新手,它是 MVFlex/Valhalla 项目的一部分。功能看起来更符合 OGNL 提供的方法调用和一些有趣的正则表达式支持。
(统一)表达式语言(https://jcp.org/aboutJava/communityprocess/final/jsr341/index.html和http://jcp.org/en/jsr/detail?id=245)标准表达式语言首次引入Java EE 5 (EL 2.1) 并在 Java EE 6 (EL 2.2) 和 Java EE 7 (EL 3.0) 中得到增强。Glassfish 项目 -统一表达式语言中提供的参考实现。
JEXL ( http://jakarta.apache.org/commons/jexl/) 基于 Velocity 解析器的实现。正因为如此,它更像是一个有限的模板解决方案,具有方法调用之类的功能。
For now I ended up with this code using BeanUtils- ugly but works.
现在我最终使用BeanUtils得到了这段代码- 丑陋但有效。
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
public static class SimpleEvaluator implements IExprLangEvaluator {
private static final org.slf4j.Logger log = LoggerFactory.getLogger( SimpleEvaluator.class );
@Override
public String evaluateEL( String template, Map<String, String> properties ) {
StringTokenizer st = new StringTokenizer( template );
String text = st.nextToken("${");
StringBuilder sb = new StringBuilder();
// Parse the template: "Hello ${person.name} ${person.surname}, ${person.age}!"
do{
try {
sb.append(text);
if( ! st.hasMoreTokens() )
break;
// "${foo.bar[a]"
String expr = st.nextToken("}");
// "foo.bar[a].baz"
expr = expr.substring(2);
// "foo"
String var = StringUtils.substringBefore( expr, ".");
Object subject = properties.get( var );
// "bar[a].baz"
String propPath = StringUtils.substringAfter( expr, ".");
sb.append( resolveProperty( subject, propPath ) );
text = st.nextToken("${");
text = text.substring(1);
} catch( NoSuchElementException ex ){
// Unclosed ${
log.warn("Unclosed ${ expression, missing } : " + template);
}
} while( true );
return sb.toString();
}
// BeanUtils
private String resolveProperty( Object subject, String propPath ) {
if( subject == null ) return "";
if( propPath == null || propPath.isEmpty() ) return subject.toString();
try {
return "" + PropertyUtils.getProperty( subject, propPath );
} catch( IllegalAccessException | InvocationTargetException | NoSuchMethodException ex ) {
log.warn("Failed resolving '" + propPath + "' on " + subject + ":\n " + ex.getMessage(), ex);
return "";
}
}
}// class SimpleEvaluator
回答by Ondra ?i?ka
I found one at http://juel.sourceforge.net/guide/start.html. Still not exactly 1-liner, but close.
我在http://juel.sourceforge.net/guide/start.html找到了一个。仍然不完全是 1-liner,但很接近。
ExpressionFactory factory = new de.odysseus.el.ExpressionFactoryImpl();
de.odysseus.el.util.SimpleContext context = new de.odysseus.el.util.SimpleContext();
context.setVariable("foo", factory.createValueExpression("bar", String.class));
ValueExpression e = factory.createValueExpression(context, "Hello ${foo}!", String.class);
System.out.println(e.getValue(context)); // --> Hello, bar!
Maven deps:
Maven 部门:
<!-- Expression language -->
<dependency>
<groupId>de.odysseus.juel</groupId>
<artifactId>juel-api</artifactId>
<version>2.2.7</version>
</dependency>
<dependency>
<groupId>de.odysseus.juel</groupId>
<artifactId>juel-impl</artifactId>
<version>2.2.7</version>
<type>jar</type>
</dependency>