Java OGNL入門(Java環境當中使用)

OGNL入門(Java環境當中使用)

創建好web工程:
引入Struts2的jar包

1、訪問對象的方法

import org.junit.Test;
import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;
/*
 * OGNL 在Java環境下的使用
 */
public class OgnlDemo1 {
	@Test
	/*
	 * OGNL如何調用對象的方法
	 */
	public void demo1() throws OgnlException {
		// 獲得context
		OgnlContext context = new OgnlContext();
		// 獲得根對象
		Object root = context.getRoot();
		// 執行表達式:
		Object obj = Ognl.getValue("'helloworld'.length()", context, root);
		System.out.println(obj);
	}
}

2、訪問對象的靜態方法

@Test
	//訪問對象靜態方法
	public void demo2() throws OgnlException {
		OgnlContext context = new OgnlContext();
		// 獲得根對象
		Object root = context.getRoot();
		// 執行表達式:@類名@方法名
		Object obj = Ognl.getValue("@java.lang.Math@random()*10", context, root);
		System.out.println(obj);
	}

3、獲得Root當中的數據

創建一個User對象

package com.itzheng.struts2.domain;
public class User {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public User() {
		// TODO Auto-generated constructor stub
	}
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
}

訪問Root當中的數據 不需要加#

	@Test
	// 訪問Root當中的數據  不需要加#
	public void demo3() throws OgnlException {
		OgnlContext context = new OgnlContext();
		// 執行表達式:@類名@方法名
		User user = new User("aaa", "123");
		context.setRoot(user);// 將User對象存儲到了root當中
		// 獲得根對象
		Object root = context.getRoot();
		// 獲取裏面User當中的用戶名和密碼
		Object username = Ognl.getValue("username", context, root);
		Object password = Ognl.getValue("password", context, root);
		System.out.println(username + "    " + password);
	}

4、獲得OgnlContext當中的數據。

@Test
	// 訪問context當中的數據  不需要加#
	public void demo4() throws OgnlException {
		OgnlContext context = new OgnlContext();
		// 執行表達式:@類名@方法名
		// 獲得根對象
		Object root = context.getRoot();
		//向context當中存入數據
		context.put("name","張三");
		//執行表達式:
		Object obj = Ognl.getValue("#name", context, root);
		System.out.println(obj);
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章