OGNL表达式

package com.cmcc.log;

import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;

public class OGNL {
    public static void main(String[] args) throws OgnlException{
        OgnlContext ognlContext = new OgnlContext();

        Object root = ognlContext.getRoot();

        Object value = Ognl.getValue("'helloworld'.length()", ognlContext, root);  //expression就是方法表达式

        System.out.println(value.toString());

        value = Ognl.getValue("@java.lang.Math@random()", ognlContext, root); //这里注意获取静态方法表达式是固定表达: @类名@方法名
        System.out.println(value.toString());

        User user = new User();
        user.setName("张三");
        ognlContext.setRoot(user);

        value = (String) Ognl.getValue("name", ognlContext, ognlContext.getRoot());
        System.out.println(value);


        ognlContext.put("name","张萨姆");

        value = (String) Ognl.getValue("#name", ognlContext, ognlContext.getRoot());
        System.out.println(value);

        value = (String) Ognl.getValue("name", ognlContext, ognlContext.getRoot());
        System.out.println(value);

        value = (String) Ognl.getValue("#name", ognlContext, new Object());
        System.out.println(value);

        value = (String)ognlContext.get("name");
        System.out.println(value);
    }
}

控制台输出:

10
0.05190743204224668
张三
张萨姆
张三
张萨姆
张萨姆

OGNL在mybatis中解析和拼接动态SQL使用较多

https://blog.csdn.net/qq_34191426/article/details/101002431

原文地址:https://www.cnblogs.com/zhangww/p/12104332.html