OGNL表达式与值栈

一、OGNL表达式

 1、java环境使用OGNL

public class OGNLDemo1 {
	
	@Test
	public void demo1() throws OgnlException {
//		获得context
		OgnlContext context = new OgnlContext();
//		获得根对象
		Object root = context.getRoot();
//		执行表达式
//		1、调用对象方法
		Object value = Ognl.getValue("'nihao'.length()", context, root);
//		2、调用对象静态方法
		Object value2 = Ognl.getValue("@[email protected]()", context, root);
		System.out.println(value2.toString());
	}
	
	@Test
	public void demo2() throws OgnlException {
		OgnlContext context = new OgnlContext();
		User user = new User("zhangsan ", 21, "male");
//		向root中存入数据
		context.setRoot(user);
		Object root = context.getRoot();
		Object username = Ognl.getValue("username", context, root);
//		OGNL获取root中的数据
		Object age = Ognl.getValue("age", context, root);
		Object sex = Ognl.getValue("sex", context, root);
		System.out.println(username.toString()+"  "+age.toString()+"  "+sex.toString());
	}
	
	@Test
	public void demo3() throws OgnlException {
//		获得context
		OgnlContext context = new OgnlContext();
//		获得根对象
		Object root = context.getRoot();
//		向context里存入数据
		context.put("name", "wangqiang");
//		执行表达式
//		OGNL获取context里的数据
		Object value = Ognl.getValue("#name", context, root);
		System.out.println(value.toString());
	}
}

2、struts标签环境使用OGNL

*注意:

要引入struts标签库

<%@ taglib uri="/struts-tags" prefix="s" %>

访问静态方法要修改静态常量值(在struts.xml中配置)

 <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>

二、值栈

1、valuestack的获得和操作

jsp页面:

action代码: 

/**
 * 操作valuestack
 * 方式一获取:利用action在值栈中的特性
 * @author xuyao
 *
 */

public class ValueStackDemo3 extends ActionSupport {
	
	private User user;
	
	@Override
	public String execute() throws Exception {
//		方式一、通过ActionContext获得
		ValueStack valueStack = ActionContext.getContext().getValueStack();
//		方式二、通过request获得
		ValueStack valueStack2 = (ValueStack) ServletActionContext.getRequest()
				.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
		user = new User("zhangsan ", 21, "male");
		return "success";
	}

	public User getUser() {
		return user;
	}
}

/**
 * 操作valuestack
 * 方式二获取:调用栈中的对象获得
 * @author xuyao
 *
 */

public class ValueStackDemo4 extends ActionSupport {
	
	@Override
	public String execute() throws Exception {
		ValueStack valueStack = ActionContext.getContext().getValueStack();
		User user = new User("lisi", 31, "male");
//		user在栈顶的位置
		valueStack.push(user);
		valueStack.set("name", "wangwu");
		return "success";
	}
	
}

 

通过ActionContext获得的方式更常用

方式二获取:调用栈中的对象获得更常用

2、获得valuestack中的数据