本文共 2280 字,大约阅读时间需要 7 分钟。
使用OGNL进行简单的测试时,获取对象的属性,结果出现报错,信息如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | Exception in thread "main" java.lang.ExceptionInInitializerError at ognl.ASTProperty.getValueBody(ASTProperty.java: 114 ) at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java: 212 ) at ognl.SimpleNode.getValue(SimpleNode.java: 258 ) at ognl.Ognl.getValue(Ognl.java: 494 ) at ognl.Ognl.getValue(Ognl.java: 644 ) at ognl.Ognl.getValue(Ognl.java: 702 ) at ognl.Ognl.getValue(Ognl.java: 672 ) at OGNL1.main(OGNL1.java: 15 ) Caused by: java.lang.IllegalArgumentException: Javassist library is missing in classpath! Please add missed dependency! at ognl.OgnlRuntime.<clinit>(OgnlRuntime.java: 168 ) ... 8 more Caused by: java.lang.ClassNotFoundException: javassist.ClassPool at java.net.URLClassLoader$ 1 .run(URLClassLoader.java: 372 ) at java.net.URLClassLoader$ 1 .run(URLClassLoader.java: 361 ) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java: 360 ) at java.lang.ClassLoader.loadClass(ClassLoader.java: 424 ) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java: 308 ) at java.lang.ClassLoader.loadClass(ClassLoader.java: 357 ) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java: 260 ) at ognl.OgnlRuntime.<clinit>(OgnlRuntime.java: 165 ) ... 8 more |
然后检查了一下发现是关键的包没有导入,使用OGNL需要导入两个关键的包,分别是:ognl-xxx.jar 和 javassist-xxx.GA.jar ,将这两个包导入后,运行正常
测试实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import ognl.Ognl; import ognl.OgnlException; public class OGNL1 { /** * @param args */ public static void main(String[] args) { Person person = new Person(); person.setName( "xiaoming" ); try { System.out.println(Ognl.getValue( "passwd" , person)); Object valueObject = Ognl.getValue( "name" , person); System.out.println(valueObject); } catch (OgnlException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Person{ public String passwd = "root" ; private String name; public String getName() { return name; } public void setName(String name) { this .name = name; } } |
注:对于有访问权限的字段,无需getter方法
输出:
root
xiaoming
本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1701364,如需转载请自行联系原作者