欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Struts2 OGNL

程序员文章站 2022-04-18 11:46:44
...

Person.java

package org.fool.ognl;

public class Person {

	private String name;

	private Dog dog;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Dog getDog() {
		return dog;
	}

	public void setDog(Dog dog) {
		this.dog = dog;
	}

}

 

Dog.java

package org.fool.ognl;

public class Dog {

	private String name;

	private String[] friends;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String[] getFriends() {
		return friends;
	}

	public void setFriends(String[] friends) {
		this.friends = friends;
	}

}

 

OgnlTest.java

package org.fool.ognl;

import java.util.ArrayList;
import java.util.List;

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

/**
 * OGNL(Object Graph Navigation Language)对象导航语言
 * 
 * OgnlContext(上下文对象),存在唯一的叫做根的对象(root), 可以通过程序设定上下文当中哪个对象作为根对象。
 * 
 * 在OGNL中,如果表达式没有使用#号,那么OGNL会从根对象中寻找 该属性对应的get方法,如果寻找的不是根对象中的属性,
 * 那么则需要以#号开头,告诉OGNL,去寻找你所指定的特定对象中的属性。
 */
public class OgnlTest {
	public static void main(String[] args) throws OgnlException {
		Person person = new Person();
		person.setName("zhangsan");

		Dog dog2 = new Dog();
		dog2.setName("wangcai2");

		person.setDog(dog2);

		Dog dog = new Dog();
		dog.setName("wangcai");

		OgnlContext context = new OgnlContext();
		context.put("person", person);
		context.put("dog", dog);

		context.setRoot(person); // 根对象

		Object object = Ognl.parseExpression("name");
		System.out.println(object);

		Object object2 = Ognl.getValue(object, context, context.getRoot());
		System.out.println(object2);

		System.out.println("-----------");

		Object object3 = Ognl.parseExpression("#person.name");
		System.out.println(object3);

		Object object4 = Ognl.getValue(object3, context, context.getRoot());
		System.out.println(object4);

		System.out.println("-----------");

		Object object5 = Ognl.parseExpression("#dog.name");
		System.out.println(object5);

		Object object6 = Ognl.getValue(object5, context, context.getRoot());
		System.out.println(object6);

		System.out.println("-----------");

		Object object7 = Ognl.parseExpression("#person.dog.name");
		System.out.println(object7);

		Object object8 = Ognl.getValue(object7, context, context.getRoot());
		System.out.println(object8);

		System.out.println("-----------");

		Object object9 = Ognl.parseExpression("name.toUpperCase()");
		System.out.println(object9);

		Object object10 = Ognl.getValue(object9, context, context.getRoot());
		System.out.println(object10);

		System.out.println("-----------");

		// 当使用OGNL调用静态方法的时候,需要按照如下语法编写表达式:
		// @[email protected](parameter)
		Object object11 = Ognl
				.parseExpression("@[email protected](10)");
		System.out.println(object11);

		Object object12 = Ognl.getValue(object11, context, context.getRoot());
		System.out.println(object12);

		System.out.println("-----------");

		// 对于OGNL来说,java.lang.Math是其的默认类,如果调用java.lang.Math的静态方法时,
		// 无需指定类的名字,比如:@@min(4, 10)
		Object object13 = Ognl.parseExpression("@@min(4, 10)");
		System.out.println(object13);

		Object object14 = Ognl.getValue(object13, context, context.getRoot());
		System.out.println(object14);

		System.out.println("-----------");

		Object object15 = Ognl.parseExpression("new java.util.LinkedList()");
		System.out.println(object15);

		Object object16 = Ognl.getValue(object15, context, context.getRoot());
		System.out.println(object16);

		// 对于OGNL来说,数组与集合是一样的,都是通过下标索引来去访问的。构造集合的时候使用{...}形式
		Object object17 = Ognl.getValue("{'aa', 'bb', 'cc', 'dd'}[3]", context,
				context.getRoot());
		System.out.println(object17);

		System.out.println("-----------");

		dog.setFriends(new String[] { "aa", "bb", "cc" });

		Object object18 = Ognl.getValue("#dog.friends[0]", context,
				context.getRoot());
		System.out.println(object18);

		System.out.println("-----OGNL操纵集合------");

		List<String> list = new ArrayList<String>();
		list.add("hello");
		list.add("world");
		list.add("hello world");

		context.put("list", list);

		System.out
				.println(Ognl.getValue("#list[2]", context, context.getRoot()));

		System.out.println("-----OGNL操纵映射------");

		// 处理OGNL来处理映射(Map)的语法格式如下所示:
		// #{'key1' : 'value1', 'key2' : 'value2', '...' : '...'}
		System.out.println(Ognl.getValue(
				"#{'key1' : 'value1', 'key2' : 'value2'}['key2']", context,
				context.getRoot()));

		System.out.println("-----过滤------");

		// 过滤(filtering):collection.{? expression}
		List<Person> persons = new ArrayList<Person>();
		Person p1 = new Person();
		Person p2 = new Person();
		Person p3 = new Person();

		p1.setName("zhangsan");
		p2.setName("lisi");
		p3.setName("wangwu");

		persons.add(p1);
		persons.add(p2);
		persons.add(p3);

		context.put("persons", persons);

		System.out.println(Ognl.getValue(
				"#persons.{? #this.name.length() > 4}.size()", context,
				context.getRoot()));
		System.out.println(Ognl.getValue(
				"#persons.{? #this.name.length() > 4}.isEmpty()", context,
				context.getRoot()));

		// OGNL针对集合提供了一些伪属性(如size, isEmpty),让我们可以通过属性的方式来调用
		// 方法(本质原因在与集合当中的很多方法并不符合JavaBean的命名规则),但我们依然可以通
		// 过调用方法来实现与伪属性相同的目的。
		System.out.println(Ognl.getValue(
				"#persons.{? #this.name.length() > 4}.size", context,
				context.getRoot()));
		System.out.println(Ognl.getValue(
				"#persons.{? #this.name.length() > 4}.isEmpty", context,
				context.getRoot()));

		System.out.println("-----------");

		// 过滤(filtering):获取集合中的第一个元素collection.{^ expression}
		System.out.println(Ognl.getValue(
				"#persons.{^ #this.name.length() > 4}[0].name", context,
				context.getRoot()));
		// 过滤(filtering):获取集合中的最后一个元素collection.{$ expression}
		System.out.println(Ognl.getValue(
				"#persons.{$ #this.name.length() > 4}[0].name", context,
				context.getRoot()));

		System.out.println("-----投影------");

		// 投影(projection):collection.{expression}
		System.out.println(Ognl.getValue("#persons.{name}", context,
				context.getRoot()));

		System.out.println("-----------");

		System.out.println(Ognl.getValue("#persons.{#this.name.length() <= 5 ? 'Hello World' : #this.name}",
				context, context.getRoot()));
	}
}
 

 

...
	<dependencies>
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>${struts-version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>${struts-version}</version>
		</dependency>
	</dependencies>
...

 

 

...
	<filter>	
  		<filter-name>struts2</filter-name>
  		<filter-class>
  			org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  		</filter-class>
	</filter>
  	<filter-mapping>
  		<filter-name>struts2</filter-name>
  		<url-pattern>/*</url-pattern>
  	</filter-mapping>
...

 

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.devMode" value="true" />
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.objectFactory" value="spring" />
	<constant name="struts.i18n.reload" value="true" />
	<constant name="struts.configuration.xml.reload" value="true" />
</struts>    

 

Student.java

 

package org.fool.bean;

import java.util.Map;

public class Student {

	private String name;

	private int age;

	private String address;

	private String[] teachers;

	private Cat cat;

	private Map<String, String> map;

	public Student() {
	}

	public Student(String name, int age, String address, String[] teachers,
			Cat cat, Map<String, String> map) {
		super();
		this.name = name;
		this.age = age;
		this.address = address;
		this.teachers = teachers;
		this.cat = cat;
		this.map = map;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String[] getTeachers() {
		return teachers;
	}

	public void setTeachers(String[] teachers) {
		this.teachers = teachers;
	}

	public Cat getCat() {
		return cat;
	}

	public void setCat(Cat cat) {
		this.cat = cat;
	}

	public Map<String, String> getMap() {
		return map;
	}

	public void setMap(Map<String, String> map) {
		this.map = map;
	}

}

 

Cat.java

 

package org.fool.bean;

public class Cat {

	private String name;
	
	private int age;
	
	private String color;
	
	public Cat() {
	}
	
	public Cat(String name, int age, String color) {
		this.name = name;
		this.age = age;
		this.color = color;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
	
}
 

OgnlAction.java

 

package org.fool.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.fool.bean.Cat;
import org.fool.bean.Student;

import com.opensymphony.xwork2.ActionSupport;

@Namespace("/")
@Result(name = "success", location = "ognl.jsp")
public class OgnlAction extends ActionSupport implements RequestAware,
		SessionAware, ApplicationAware {

	private String username;
	private String password;

	private Map<String, Object> requestMap;
	private Map<String, Object> sessionMap;
	private Map<String, Object> applicationMap;

	private List<Student> list = new ArrayList<Student>();

	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 List<Student> getList() {
		return list;
	}

	public void setList(List<Student> list) {
		this.list = list;
	}

	@Override
	public void setApplication(Map<String, Object> application) {
		this.applicationMap = application;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.sessionMap = session;
	}

	@Override
	public void setRequest(Map<String, Object> request) {
		this.requestMap = request;
	}

	@Action(value = "ognlAction")
	public String execute() throws Exception {
		requestMap.put("hello", "groovy");
		sessionMap.put("hello", "grails");
		applicationMap.put("hello", "jquery");

		Cat cat1 = new Cat("cat1", 20, "red");
		Cat cat2 = new Cat("cat2", 30, "blue");

		String[] teachers1 = { "hello1", "hello2", "hello3" };
		String[] teachers2 = { "world1", "world2", "world3" };

		Map<String, String> map1 = new HashMap<String, String>();
		Map<String, String> map2 = new HashMap<String, String>();

		map1.put("hello1", "hello1");
		map1.put("hello2", "hello2");

		map2.put("world1", "world1");
		map2.put("world2", "world2");

		Student student1 = new Student("zhangsan", 20, "beijing", teachers1,
				cat1, map1);
		Student student2 = new Student("lisi", 30, "shanghai", teachers2, cat2,
				map2);

		list.add(student1);
		list.add(student2);

		return SUCCESS;
	}

}
 

ognl.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="com.opensymphony.xwork2.ActionContext" %>
<%@ page import="com.opensymphony.xwork2.util.ValueStack" %>
<%@ page import="org.fool.action.OgnlAction" %>
<%@ page import="java.util.Map" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>ognl.jsp</title>
  </head>
  
  <body>
  
	username:<s:property value="username"/><br>
	password:<s:property value="password"/><br>
	
	<hr>
	
	username:<s:property value="#parameters.username"/><br>
	password:<s:property value="#parameters.password"/><br>
	
	<hr>
	
	request:<s:property value="#request.hello"/><br>
	session:<s:property value="#session.hello"/><br>
	application:<s:property value="#application.hello"/><br>
	attr:<s:property value="#attr.hello"/><br>
	
	<hr>
	
	request:<%= ((Map) ActionContext.getContext().get("request")).get("hello") %><br>
	session:<%= ActionContext.getContext().getSession().get("hello") %><br>
	application:<%=ActionContext.getContext().getApplication().get("hello") %><br>
	attr:<%= ((Map) ActionContext.getContext().get("attr")).get("hello")%>
	
	<hr>
	
	student1.address:<s:property value="list[0].address"/><br>
	student2.age:<s:property value="list[1].age"/><br>
	student1.cat.name:<s:property value="list[0].cat.name"/><br>
	size:<s:property value="list.size"/><br>
	isEmpty:<s:property value="list.isEmpty"/><br>
	
	<hr>
	
	student1.address:<%= ((OgnlAction) ActionContext.getContext().getValueStack().peek()).getList().get(0).getAddress() %><br>
	student2.age:<%= ((OgnlAction) ActionContext.getContext().getValueStack().peek()).getList().get(1).getAge() %><br>
  	student1.cat.name:<%= ((OgnlAction) ActionContext.getContext().getValueStack().peek()).getList().get(0).getCat().getName() %><br>
  
  	<hr>
  	
  	student2.friend:<s:property value="list[1].teachers[2]"/><br>
  	student2.friend:<%= ((OgnlAction) ActionContext.getContext().getValueStack().peek()).getList().get(1).getTeachers()[2] %><br>
 
 	<hr>
 	
 	student2.map2:<s:property value="list[1].map['world2']"/><br>
 	
 	<hr>
 	
 	filtering:<s:property value="list.{? #this.name.length() > 2}[1].name"/><br>
 	
 	<hr>
 	
 	<s:iterator value="list.{? #this.name.length() > 2}">
 		<s:property value="name"/><br>
 		<s:property value="cat.color"/><br>
 		<s:property value="teachers[0]"/><br>	
 	</s:iterator>
 	
 	<hr>
 	
 	projection:<br>
 	<s:iterator value="list.{age}">
 		<s:property/><br>
 	</s:iterator>
 	
  </body>
</html>