---
title: "OGNL"
author: "elihe2011"
date: "2013-08-27T22:56:57Z"
tags: []
categories: ["企业架构"]
slug: "ognl"
draft: false
lastmod: "2013-08-27T22:56:57Z"
id: 1931214
url: "https://elihe2011.iteye.com/blog/1931214"
---

OGNL: Object Graph Navigation Language

 

ActionContext类的常用方法 

1\) Object get(Object key) ：通过参数key来查找当前ActionContext中的值 

2\) Map getApplication() ：返回一个Application级的Map对象 

3\) static ActionContext getContext() ：获得当前线程的ActionContext对象 

4\) Map getParameters() ：返回一个包含所有HttpServletRequest参数信息的Map对象 

5\) Map getSession() ：返回一个Map类型的HttpSession对象 

6\) void put(Object key,Object value) ：向当前ActionContext对象中存入名值对信息 

7\) void setApplication(Map application) ：设置Application上下文 

8\) void setSession(Map session) ：设置一个Map类型的Session值

 

ActionContext中的内容： 

              |--request

              |--application

              |--session

context map---|--OgnlValueStack(root)\[user,action,OgnlUtil,…]

              |--request

              |--parameters

              |--attr (searches page, request, session, then application scopes)

 

引用Action的属性:

       &lt;s:property value="name"/&gt;

 

ActionContext对象访问：

      &lt;s:property value="#session.id" /&gt; 

      &lt;s:property value="#session\['id']" /&gt; 

      &lt;s:property value="#request\['name']" /&gt;

 

Action类使用ActionContext中的静态方法

      ActionContext.getContext().getSession().put("id", id);

 

OGNL与Collection（List, Map, Set）

1\) 生成List: {e1,e2,e3}.

    &lt;s:select label="label" name="name" list="{'name1','name2','name3'}" value="%{'name2'}" /&gt;

 

2\) 生成Map：#{key1:value1,key2:value2}.

    &lt;s:select label="label" name="name" list="#{'k1':'val1', 'k2':'val2'}" /&gt;

 

3\) 判断一个对象是否在List中存在：

   &lt;s:if test="'name2' in {'name1','name2'}"&gt;

 

   &lt;/s:if&gt;

 

4\) 取得一个List的一部分：

?    所有满足选择逻辑的对象

^   第一个满足选择逻辑的对象

$    最后一个满足选择逻辑的对象

 

person.relatives.{? #this.gender == 'male'}     // 获取person所有male的relatives

 

5\) Lambda 表达式，语法为  :\[...]，#this表示表达式的参数。

Fibonacci:

if n==0 return 0;

elseif n==1 return 1;

else return fib(n-2)+fib(n-1);

 

fib(0) = 0

fib(1) = 1

fib(11) = 89

 

&lt;s:property value="#fib = :\[#this==0 ? 0 : #this==1 ? 1 : #fib(#this-2)+#fib(#this-1)], #fib(11)" /&gt;

#fib =:\[#this==0 ? 0 : #this==1 ? 1 : #fib(#this-2)+#fib(#this-1)]定义了一个Lambda表达式，

 

#fib(11) 调用了这个表达式。

 

在JSP2.1中#被用作了JSP EL（表达式语言）的特殊记好，所以对OGNL的使用可能导致问题，

禁用JSP2.1的EL特性，修改web.xml文件：

&lt;jsp-config&gt;

    &lt;jsp-property-group&gt;

        &lt;url-pattern&gt;\*.jsp&lt;/url-pattern&gt;

        &lt;el-ignored&gt;true&lt;/el-ignored&gt;

    &lt;/jsp-property-group&gt;

&lt;/jsp-config&gt;

 

&lt;%@  page isELIgnored="true"%&gt; 表示是否禁用EL语言,TRUE表示禁止.FALSE表示不禁止.JSP2.0中默认的启用EL语言.

 

Servlet, OGNL, EL取值对比

 

Servlet OGNL EL   

parameters request.getParameter(“id”) #paramters.id\[0] ${param.id}, ${paramValues.id}   

resuqest request.getAttribute(“id”) #request.id ${requestScope.id}   

session session.getAttribute(“id”) #session.id ${sessionScope.id}   

application application.getAttribute(“id”) #application.id ${applicationScope.id}   

attr #attr.id ${id}  

 

OGNL的三个符号

1\. #

1\) 访问非根对象属性，相当于AtcionContext.getContext()

   #session.msg  &lt;=&gt; ActionContext.getContext().getSession().getAttribute("msg");

2\) 过滤集合

   students.{?#this.age&gt;15}       // 返回年龄所有大于15的学生列表

  students.{^#this.age&gt;15}       // 返回年龄第一个大于15的学生

   students.{$#this.age&gt;15}       // 返回年龄最后一个大于15的学生

 

3\) 投影(projecting)集合

  objects.{#this instanceof String ? #this : #this.toString()}

4\) 构造Map

   #{'k1':'val1', 'k2':'val2'}

 

2\. %

在标志的属性为字符串类型时，计算OGNL表达式的值

&lt;s:set name="foobar: value="#{'k1':'val1', 'k2':'val2'}"

&lt;p&gt;The value of key "k1" is &lt;s:property value="#foobar\['k1']"/&gt;&lt;/p&gt;

&lt;p&gt;The value of key "k1" is &lt;s:property value="%{#foobar\['k1']}"/&gt;&lt;/p&gt;

 

3\. $

1\) i18n或struts.xml

  &lt;action name="AddPhoto" class="addPhoto"&gt; 

         &lt;interceptor-ref name="fileUploadStack" /&gt;             

         &lt;result type="redirect"&gt;ListPhotos.action?albumId=${albumId}&lt;/result&gt; 

  &lt;/action&gt;

 

2\) 校验器

&lt;validators&gt;

    &lt;field name="score"&gt;

        &lt;field-validator type="int"&gt;

            &lt;param name="min"&gt;0&lt;/param&gt;

            &lt;param name="max"&gt;100&lt;/param&gt;

            &lt;message&gt;分数在${min}至${max}之间!&lt;/message&gt;

        &lt;/field-validator&gt;

    &lt;/field&gt;

&lt;/validators&gt;

 

EL运算符：.和\[]  存在非数字字母符号，必须使用\[]

${user.My-Name} 应当改为 ${user\["My-Name"]}

 

EL隐式对象：

 

类别 标识符 描述   

JSP pageContext PageContext 实例对应于当前页面的处理   

作用域 pageScope 与页面作用域属性的名称和值相关联的 Map 类   

  requestScope 与请求作用域属性的名称和值相关联的 Map 类   

  sessionScope 与会话作用域属性的名称和值相关联的 Map 类   

  applicationScope 与应用程序作用域属性的名称和值相关联的 Map 类   

请求参数 param 按名称存储请求参数的主要值的 Map 类   

  paramValues 将请求参数的所有值作为 String 数组存储的 Map 类   

请求头 header 按名称存储请求头主要值的 Map 类   

  headerValues 将请求头的所有值作为 String 数组存储的 Map 类   

Cookie cookie 按名称存储请求附带的 cookie 的 Map 类   

初始化参数 initParam 按名称存储 Web 应用程序上下文初始化参数的 Map 类  

 

1\. param &  paramValues

${param.name}   &lt;=&gt;   request.getParamter(name)

${paramValues.name}  &lt;=&gt; request.getParamterValues(name)

 

2\. cookie

${cookie.userCountry}

 

3\. header & headerValues 存储浏览器和服务器间通信的数据

${header\["User-Agent"]}  // 浏览器版本

 

4\. initParam web应用程序上下文初始化参数

${initParam.userid}  &lt;=&gt;  String userid = (String)application.getInitParameter("userid");

 

5\. pageContext

${pageContext.request.queryString}        // 取得请求的参数字符串

${pageContext.request.requestURL}         // 取得请求的URL，但不包括请求之参数字符串

${pageContext.request.contextPath}        // 服务的web application 的名称

${pageContext.request.method}              // 取得HTTP 的方法(GET、POST)  

${pageContext.request.protocol}             // 取得使用的协议(HTTP/1.1、HTTP/1.0)  

${pageContext.request.remoteUser}         // 取得用户名称

${pageContext.request.remoteAddr }        // 取得用户的IP 地址

${pageContext.session.new}                    // 判断session 是否为新的

${pageContext.session.id}                       // 取得session 的ID  

${pageContext.servletContext.serverInfo}  // 取得主机端的服务信息