java框架篇---struts之OGNL详解

OGNL(Object Graph Navigation Language),是一种表达式语言。使用这种表达式语言,你可以通过某种表达式语法,存取Java对象树中的任意属性、调用Java对象树的方法、同时能够自动实现必要的类型转化。如果我们把表达式看做是一个带有语义的字符串,那么OGNL无疑成为了这个语义字符串与Java对象之间沟通的桥梁。既然OGNL那么强大,那么让我们一起来研究一下他的API,看看如何使用OGNL.

OGNL的API看起来就是两个简单的静态方法:

  •   public static Object getValue( Object tree, Map context, Object root ) throws OgnlException;
  •   public static void setValue( Object tree, Map context, Object root, Object value ) throws OgnlException
1.OGNL表达式的计算是围绕OGNL上下文进行的。
OGNL上下文实际上就是一个Map对象,由ognl.OgnlContext类表示。它里面可以存放很多个JavaBean对象。它有一个上下文根对象。
上下文中的根对象可以直接使用名来访问或直接使用它的属性名访问它的属性值。否则要加前缀“#key”。
2.Struts2的标签库都是使用OGNL表达式来访问ActionContext中的对象数据的。如:<s:propertyvalue="xxx"/>。
3.Struts2将ActionContext设置为OGNL上下文,并将值栈作为OGNL的根对象放置到ActionContext中。
4.值栈(ValueStack) :
可以在值栈中放入、删除、查询对象。访问值栈中的对象不用“#”。
Struts2总是把当前Action实例放置在栈顶。所以在OGNL中引用Action中的属性也可以省略“#”。
5.调用ActionContext的put(key,value)放入的数据,需要使用#访问。

OGNL中重要的3个符号:#、%、$:

“#”主要有三种用途:

  • 访问OGNL上下文和Action上下文,#相当于ActionContext.getContext();下表有几个ActionContext中有用的属性:
  • 名称
    作用
    例子
    parameters
    包含当前HTTP
    请求参数的Map
    #parameters.id[0]
    作用相当于
    request.getParameter("id")
    request
    包含当前
    HttpServletRequest
    的属性
    (attribute)的Map
    #request.userName相当于
    request.getAttribute("userName")
    session
    包含当前
    HttpSession的
    属性(attribute)
    的Map
    #session.userName相当于
    session.getAttribute("userName")
    application
    包含当前应用的
    ServletContext
    的属性(attribute)
    的Map
    #application.userName相当于
    application.getAttribute("userName")
    attr
    用于按request >
    session > application
    顺序访问其属性
    (attribute)
    #attr.userName相当于
    按顺序在以上三个范围(scope)
    内读取userName属性,直到找到为止
  • 用于过滤和投影(projecting)集合,如books.{?#this.price<100};
  • 构造Map,如#{'foo1':'bar1', 'foo2':'bar2'}。

"%“符号

%符号的用途是在标志的属性为字符串类型时,计算OGNL表达式的值,这个类似js中的eval,很暴力。

"$"符号

$符号主要有两个方面的用途。

—    在国际化资源文件中,引用OGNL表达式,例如国际化资源文件中的代码:reg.agerange=国际化资源信息:年龄必须在${min}同${max}之间。

—    在Struts 2框架的配置文件中引用OGNL表达式,例如:

<action name="AddPhoto" class="addPhoto">
            <interceptor-ref name="fileUploadStack" />
            <result type="redirect">ListPhotos.action?albumId=${albumId}</result>
 </action>

下面代码实例对OGNL有更深的了解:

Cat.java
package com.oumyye.struts2.ognl;

public class Cat {
    
    private Dog friend;
    
    public Dog getFriend() {
        return friend;
    }

    public void setFriend(Dog friend) {
        this.friend = friend;
    }

    public String miaomiao() {
        return "miaomiao";
    }
}
Dog.java
package com.oumyye.struts2.ognl;

public class Dog {
    
    private String name;
    
    public Dog() {
        
    }

    public Dog(String name) {
        super();
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "dog: " + name;
    }
}
User.java
package com.oumyye.struts2.ognl;

public class User {
    private int age = 8;
    
    public User() {
        
    }
    
    public User(int age) {
        super();
        this.age = age;
    }


    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "user" + age;
    }
}

OgnlAction.java
package com.oumyye.struts2.ognl;

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

import com.opensymphony.xwork2.ActionSupport;

public class OgnlAction extends ActionSupport {
    private Cat cat;
    private Map<String, Dog> dogMap = new HashMap<String, Dog>();

    private Set<Dog> dogs = new HashSet<Dog>();

    private String password;

    private User user;
    private String username;

    private List<User> users = new ArrayList<User>();

    public OgnlAction() {
        users.add(new User(1));
        users.add(new User(2));
        users.add(new User(3));

        dogs.add(new Dog("dog1"));
        dogs.add(new Dog("dog2"));
        dogs.add(new Dog("dog3"));
        
        dogMap.put("dog100", new Dog("dog100"));
        dogMap.put("dog101", new Dog("dog101"));
        dogMap.put("dog102", new Dog("dog102"));
        
    }

    public String execute() {
        return SUCCESS;
    }

    public Cat getCat() {
        return cat;
    }
    
    public Map<String, Dog> getDogMap() {
        return dogMap;
    }

    public Set<Dog> getDogs() {
        return dogs;
    }
    
    public String getPassword() {
        return password;
    }
    
    public User getUser() {
        return user;
    }

    public String getUsername() {
        return username;
    }

    public List<User> getUsers() {
        return users;
    }

    public String m() {
        return "hello";
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }
    
    public void setDogMap(Map<String, Dog> dogMap) {
        this.dogMap = dogMap;
    }

    public void setDogs(Set<Dog> dogs) {
        this.dogs = dogs;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }
}

ognl.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>OGNL表达式语言学习</title>
</head>
<body>
    <ol>
        <li>访问值栈中的action的普通属性: username = <s:property value="username"/> </li>
        <li>访问值栈中对象的普通属性(get set方法):<s:property value="user.age"/> | <s:property value="user['age']"/> | <s:property value="user["age"]"/> | wrong: <%--<s:property value="user[age]"/>--%></li>
        <li>访问值栈中对象的普通属性(get set方法): <s:property value="cat.friend.name"/></li>
        <li>访问值栈中对象的普通方法:<s:property value="password.length()"/></li>
        <li>访问值栈中对象的普通方法:<s:property value="cat.miaomiao()" /></li>
        <li>访问值栈中action的普通方法:<s:property value="m()" /></li>
        <hr />
        <li>访问静态方法:<s:property value="@com.oumyye.struts2.ognl.S@s()"/></li>
        <li>访问静态属性:<s:property value="@com.oumyye.struts2.ognl.S@STR"/></li>
        <li>访问Math类的静态方法:<s:property value="@@max(2,3)" /></li>
        <hr />
        <li>访问普通类的构造方法:<s:property value="new com.oumyye.struts2.ognl.User(8)"/></li>
        <hr />
        <li>访问List:<s:property value="users"/></li>
        <li>访问List中某个元素:<s:property value="users[1]"/></li>
        <li>访问List中元素某个属性的集合:<s:property value="users.{age}"/></li>
        <li>访问List中元素某个属性的集合中的特定值:<s:property value="users.{age}[0]"/> | <s:property value="users[0].age"/></li>
        <li>访问Set:<s:property value="dogs"/></li>
        <li>访问Set中某个元素:<s:property value="dogs[1]"/></li>
        <li>访问Map:<s:property value="dogMap"/></li>
        <li>访问Map中某个元素:<s:property value="dogMap.dog101"/> | <s:property value="dogMap['dog101']"/> | <s:property value="dogMap["dog101"]"/></li>
        <li>访问Map中所有的key:<s:property value="dogMap.keys"/></li>
        <li>访问Map中所有的value:<s:property value="dogMap.values"/></li>
        <li>访问容器的大小:<s:property value="dogMap.size()"/> | <s:property value="users.size"/> </li>
        <hr />
        <li>投影(过滤):<s:property value="users.{?#this.age==1}[0]"/></li>
        <li>投影:<s:property value="users.{^#this.age>1}.{age}"/></li>
        <li>投影:<s:property value="users.{$#this.age>1}.{age}"/></li>
        <li>投影:<s:property value="users.{$#this.age>1}.{age} == null"/></li>
        <hr />
        <li>[]:<s:property value="[0].username"/></li>
        
    </ol>
    
    <s:debug></s:debug>
</body>
</html>

index.jsp

<?xml version="1.0" encoding="GB18030" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String contextPath = request.getContextPath();
 %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
    访问属性
    <a href="<%=contextPath %>/ognl.action?username=u&password=p">ognl</a>
</body>
</html>

Struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
 <constant name="struts.enable.DynamicMethodInvocation" value="false" />
   
    <constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
    <package name="ognl" extends="struts-default">

        <action name="ognl" class="com.oumyye.struts2.ognl.OgnlAction">
            <result>/ognl.jsp</result>
        </action>
        <action name="test" class="com.oumyye.struts2.ognl.TestAction">
            <result type="chain">ognl</result>
        </action>

    </package>
</struts>

结果如下

原文地址:https://www.cnblogs.com/oumyye/p/4361812.html