标签:
package cn.lyjs.ognl; import org.junit.Test; import ognl.Ognl; import ognl.OgnlContext; import ognl.OgnlException; public class OgnlDemo1 { /** * Ognl表达式语言取值,取非根元素必须使用#, * 如果取根元素的值,不需要带#号 * @throws OgnlException */ @Test public void testOgnl() throws OgnlException { //创建一个Ognl上下文对象 OgnlContext context=new OgnlContext(); //放入数据 User user=new User(); user.setId(20); user.setName("Tom"); context.put("user", user); //获取数据 //先构建一个Ognl表达式,在解析表达式 Object ognl=Ognl.parseExpression("#user.id"); Object value=Ognl.getValue(ognl, context, context.getRoot()); System.out.println(value); } @Test public void testOgn2() throws OgnlException { //创建一个Ognl上下文对象 OgnlContext context=new OgnlContext(); //放入数据 User user=new User(); user.setId(20); user.setName("Tom"); context.setRoot(user); //获取数据 //先构建一个Ognl表达式,在解析表达式 Object ognl=Ognl.parseExpression("id"); Object value=Ognl.getValue(ognl, context, context.getRoot()); System.out.println(value); } /** * Ognl对静态方法调用的支持 * @throws OgnlException */ @Test public void testOgnl3() throws OgnlException { //创建一个Ognl上下文对象 OgnlContext context=new OgnlContext(); //Ognl表达式语言,代用类的静态方法 //Object ognl=Ognl.parseExpression("@Math@floor(10.9)"); //由于Math类在开发中比较常用所以也可以这样写 Object ognl=Ognl.parseExpression("@@floor(10.9)"); Object value=Ognl.getValue(ognl, context, context.getRoot()); System.out.println(value); } }
package cn.lyjs.ognl; import static org.junit.Assert.*; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.junit.Test; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; public class OgnlDemo2 extends ActionSupport{ @Override public String execute() throws Exception { gets(); return SUCCESS; } private void gets() { //获取值栈对象 HttpServletRequest request = ServletActionContext.getRequest(); ValueStack vs2 = (ValueStack) request.getAttribute("struts.valueStack"); //获取值栈对象 ActionContext ac=ActionContext.getContext(); ValueStack valueStack = ac.getValueStack(); } }
标签:
原文地址:http://www.cnblogs.com/lyjs/p/5094887.html