在struts2 中使用OGNL时经常会遇到“#”,"%","$",具体用法绕到头晕 ,在网上找到下面的介绍 ,故整理摘记,防止一晕到底。
“#”主要有3种用途,
1.访问OGNL上下文和Action上下文 ,相当于ActionContext.getContext();下面是几个ActionContext 中有用的属性
parameter : #parameter.id[0] ~~request.getParameter("id");
request : #request.id ~~request.getAttribute("id");
session : #session.id ~~session.getAttribute("id");
application: #application.id ~~application.getAttribute("id");
attr : #attr.id ~~依次按照request ->session ->application 顺序查找id属性的值。
2用于过滤和投影集合,如 books.{?#this.price <100};
3.够着Map ,如 #{‘foo’:‘ak’,'boo':'kk'};
"%"用途是在标志属性为字符串的时候用于计算OGNL表达式的值。
如 <s:url value = "%{#foobar['foo']}"/>
$主要有两种用途
1.在国际化资源文件中引用OGNL表达式。
2.在struts2配置文件中使用OGNL表达式。
找到的一段示例代码
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title></title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- </head>
-
- <body>
- ognl.jsp.....................<br>
- 编号: <s:property value="id"/><br>
- 地址:<s:property value="address"/><br>
- User对象:<s:property value="user"/><br>
- userName:<s:property value="user.userName"/><br>
- userPwd:<s:property value="user.userPwd"/><br>
- userList集合:<s:property value="userList"/><br>
- list size:<s:property value="userList.size"/><br>
- 第一个对象:<s:property value="userList[0]"/><br>
- 投影<br>
- 取得List中所有的姓名:<s:property value="userList.{userName}"/><br>
- 取得List中第一个对象的姓名:<s:property value="userList.{userName}[0]"/>
- 输出List中姓名为tom的所有用户对象:<br>
- <s:property value="userList.{?#this.userName=='tom'}"/><br>
- 输出List中姓名为tom的第一个用户对象:<br>
- <s:property value="userList.{^#this.userName=='tom'}"/><br>
- 输出List中姓名为tom的最后一个用户对象:<br>
- <s:property value="userList.{$#this.userName=='tom'}"/><br>
-
- OGNL操作Map集合--------------------<br>
- 输出Map中的key:<s:property value="userMap.keys"/><br>
- 输出Map中的value:<s:property value="userMap.values"/><br>
- 输出Map中的数量:<s:property value="userMap.size"/><br>
- 输出key(tom)对应的value:<s:property value="userMap['tom'].{id}[0]"/><br>---
- 判断Map是否为empty:<s:property value="userMap.isEmpty"/><br>
-
- 动态创建List和Map ---------------------------<br>
- 动态创建List:<s:property value="{'aa','bb','cc'}"/>
- 动态创建Map:<s:property value="#{'aa':'aa','bb':'bb'}"/>
- <br>
- 获取request session Application中的值--------------------------<br>
- 获取Session中的值:<br>
- <s:property value="#session.sessionKey"/><br>
- 获取reuqst中的值:<br>
- <s:property value="#request.requestKey"/><br>
- 获取Application中的值:<br>
- <s:property value="#application.applicationKey"/>
- </body>
- </html>
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。