Struts 2中的表达式语言

Struts 2支持以下几种表达式语言:

OGNL(Object-Graph Navigation Language),可以方便地操作对象属性的开源表达式语言;
JSTL(JSP Standard Tag Library),JSP 2.0集成的标准的表达式语言;
Groovy,基于Java平台的动态语言,它具有时下比较流行的动态语言(如Python、Ruby和Smarttalk等)的一些起特性;
Velocity,严格来说不是表达式语言,它是一种基于Java的模板匹配引擎,具说其性能要比JSP好。
Struts 2默认的表达式语言是OGNL,原因是它相对其它表达式语言具有下面几大优势:

支持对象方法调用,如xxx.doSomeSpecial();
支持类静态的方法调用和值访问,表达式的格式为@[类全名(包括包路径)]@[方法名 | 值名],例如:@java.lang.String@format('foo %s', 'bar')或@tutorial.MyConstant@APP_NAME;
支持赋值操作和表达式串联,如price=100, discount=0.8, calculatePrice(),这个表达式会返回80;
访问OGNL上下文(OGNL context)和ActionContext;
操作集合对象。
OGNL的用法
OGNL是通常要结合Struts 2的标志一起使用,如<s:property value="xx" />等。大家经常遇到的问题是#、%和$这三个符号的使用。下面我想通过例子讲述这个问题:

首先新建名为Struts2_OGNL的Web工程,配置开发环境。之前很多朋友在使用Struts 2的过程中都遇到乱码问题。当然乱码问题由来已久,而且涉及多方面的知识,所以并非三言两语可以说明白,而且互联网上也已经有很多这方便的文章,大家可以Google一下。不过,如果你在开发的过程,多注意一下,避免乱码问题也不难。乱码多数是由于编码与解码所使用的方式不同造成的,所以我建议大家将编码方式都设为“utf-8”,如<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>。另外,在配置web.xml时使用ActionContextCleanUp过滤器(Filter),如下面代码所示:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Struts 2 OGNL</display-name>

<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>清单1 WebContent/WEB-INF/web.xml
“#”主要有三种用途:

访问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'}。
下面让我们它们的具体写法,首先是Action类代码:

package tutorial.action;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.util.ServletContextAware;

import tutorial.model.Book;

import com.opensymphony.xwork2.ActionSupport;

public class OgnlAction extends ActionSupport implements ServletRequestAware, SessionAware, ServletContextAware {
private static final long serialVersionUID = 1L;

private HttpServletRequest request;
private Map<String, String> session;
private ServletContext application;
private List<Book> books;

public void setServletRequest(HttpServletRequest request) {
this.request = request;
}

@SuppressWarnings("unchecked")
public void setSession(Map session) {
this.session = session;
}

public void setServletContext(ServletContext application) {
this.application = application;
}

public List<Book> getBooks() {
return books;
}

@Override
public String execute() {
request.setAttribute("userName", "Max From request");
session.put("userName", "Max From session");
application.setAttribute("userName", "Max From application");

books = new LinkedList<Book>();
books.add(new Book("978-0735619678", "Code Complete, Second Edition", 32.99));
books.add(new Book("978-0596007867", "The Art of Project Management", 35.96));
books.add(new Book("978-0201633610", "Design Patterns: Elements of Reusable Object-Oriented Software", 43.19));
books.add(new Book("978-0596527341", "Information Architecture for the World Wide Web: Designing Large-Scale Web Sites", 25.19));
books.add(new Book("978-0735605350", "Software Estimation: Demystifying the Black Art", 25.19));

return SUCCESS;
}
}清单2 src/tutorial/action/OgnlAction.java

以上代码分别在request、session和application的范围内添加“userName”属性,然后再在JSP页面使用OGNL将其取回。我还创建了Book对象的列表用于演示“用于过滤和投影(projecting)集合”的功能,至于Book的代码大家可以在我前一文章《在Struts 2中实现CRUD》看到。

下面是Ognl.jsp的代码,内容如下:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

<!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>
<title>Struts OGNL Demo</title>
</head>
<body>
<h3>访问OGNL上下文和Action上下文</h3>
<p>parameters: <s:property value="#parameters.userName" /></p>
<p>request.userName: <s:property value="#request.userName" /></p>
<p>session.userName: <s:property value="#session.userName" /></p>
<p>application.userName: <s:property value="#application.userName" /></p>
<p>attr.userName: <s:property value="#attr.userName" /></p>
<hr />
<h3>用于过滤和投影(projecting)集合</h3>
<p>Books more than $35</p>
<ul>
<s:iterator value="books.{?#this.price > 35}">
<li><s:property value="title" /> - $<s:property value="price" /></li>
</s:iterator>
</ul>
<p>The price of "Code Complete, Second Edition" is: <s:property value="books.{?#this.title=='Code Complete, Second Edition'}.{price}[0]"/></p>
<hr />
<h3>构造Map</h3>
<s:set name="foobar" value="#{'foo1':'bar1', 'foo2':'bar2'}" />
<p>The value of key "foo1" is <s:property value="#foobar['foo1']" /></p>
</body>
</html>清单3 WebContent/Ognl.jsp
以上代码值得注意的是“<s:property value="books.{?#this.title=='Code Complete, Second Edition'}.{price}[0]"/>”,因为“books.{?#this.title=='Code Complete, Second Edition'}.{price}”返回的值是集合类型,所以要用“[索引]”来访问其值。

最后是Struts 2的配置文件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.devMode" value="true" />
<package name="Struts2_OGNL_DEMO" extends="struts-default">
<action name="Ognl" class="tutorial.action.OgnlAction">
<result>/Ognl.jsp</result>
</action>
</package>
</struts>清单4 src/struts.xml

发布运行应用程序,结果如下所示:


清单5 示例运行结果1

“%”符号的用途是在标志的属性为字符串类型时,计算OGNL表达式的值。例如在Ognl.jsp中加入以下代码:

<hr />
<h3>%的用途</h3>
<p><s:url value="#foobar['foo1']" /></p>
<p><s:url value="%{#foobar['foo1']}" /></p>清单6 演示%用途的代码片段
刷新页面,结果如下所示:

清单7 示例运行结果2

“$”有两个主要的用途

用于在国际化资源文件中,引用OGNL表达式,例子如下:
国际化是商业系统中不可或缺的一部分,所以无论您学习的是什么Web框架,它都是必须掌握的技能。

其实,Struts 1.x在此部分已经做得相当不错了。它极大地简化了我们程序员在做国际化时所需的工作,例如,如果您要输出一条国际化的信息,只需在代码包中加入FILE-NAME_xx_XX.properties(其中FILE-NAME为默认资源文件的文件名),然后在struts-config.xml中指明其路径,再在页面用<bean:message>标志输出即可。

不过,所谓“没有最好,只有更好”。Struts 2.0并没有在这部分止步,而是在原有的简单易用的基础上,将其做得更灵活、更强大。

国际化Hello World
下面让我们看一个例子——HelloWorld。这个例子演示如何根据用户浏览器的设置输出相应的HelloWorld。

在Eclipse创建工程配置开发和运行环境(如果对这个步骤有问题,可以参考我早前的文章《为Struts 2.0做好准备》)。

在src文件夹中加入struts.properties文件,内容如下:
struts.custom.i18n.resources=globalMessages
Struts 2.0有两个配置文件,struts.xml和struts.properties都是放在WEB-INF/classes/下。
struts.xml用于应用程序相关的配置
struts.properties用于Struts 2.0的运行时(Runtime)的配置


在src文件夹中加入globalMessages_en_US.properties文件,内容如下:
HelloWorld=Hello World!
在src文件夹中加入globalMessages_zh_CN.properties文件,内容如下:
HelloWorld=你好,世界! 在此想和大家分享一个不错的编写properties文件的Eclipse插件(plugin),有了它我们在编辑一些简体中文、繁体中文等Unicode文本时,就不必再使用native2ascii编码了。您可以通过Eclipse中的软件升级(Software Update)安装此插件,步骤如下:

1、展开Eclipse的Help菜单,将鼠标移到Software Update子项,在出现的子菜单中点击Find and Install;
2、在Install/Update对话框中选择Search for new features to install,点击Next;
3、在Install对话框中点击New Remote Site;
4、在New Update Site对话框的Name填入“PropEdit”或其它任意非空字符串,在URL中填入http://propedit.sourceforge.jp/eclipse/updates/;
5、在Site to include to search列表中,除上一步加入的site外的其它选项去掉,点击Finsih;
6、在弹出的Updates对话框中的Select the features to install列表中将所有结尾为“3.1.x”的选项去掉(适用于Eclipse 3.2版本的朋友);
7、点击Finish关闭对话框;
8、在下载后,同意安装,再按提示重启Eclipse,在工具条看到形似vi的按钮表示安装成功,插件可用。此时,Eclpise中所有properties文件的文件名前有绿色的P的图标作为标识。

在WebContent文件夹下加入HelloWorl.jsp文件,内容如下:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2><s:text name="HelloWorld"/></h2>
<h2><s:property value="%{getText('HelloWorld')}"/></h2>
</body>
</html>
发布运行应用程序,在浏览器地址栏中输入http://localhost:8080/Struts2_i18n/HelloWorld.jsp
http://www.blogjava.net/max/archive/2006/11/01/78536.aspx


在Struts 2配置文件中,引用OGNL表达式,如 <action name="AddPhoto" class="addPhoto">
<interceptor-ref name="fileUploadStack" />
<result type="redirect">ListPhotos.action?albumId=${albumId}</result>
</action>清单8 演示$用途的代码片段
总结
OGNL是一种功能很大的表达式语言,熟悉它可以使我们的开发变得更快捷。


OGNL表达式

OGNL,全称为Object-Graph Navigation Language,它是一个功能强大的表达式语言,用来获取和设置Java对象的属性,它旨在提供一个更高的更抽象的层次来对Java对象图进行导航。

OGNL表达式的基本单位是"导航链",一般导航链由如下几个部分组成:

属性名称(property)
方法调用(method invoke)
数组元素
所有的OGNL表达式都基于当前对象的上下文来完成求值运算,链的前面部分的结果将作为后面求值的上下文。例如:names[0].length()。

示例:第一个OGNL程序

public class OGNL1 { public static void main(String[] args) { /* 创建一个Person对象 */ Person person = new Person(); person.setName("zhangsan"); try { /* 从person对象中获取name属性的值 */ Object value = Ognl.getValue("name", person); System.out.println(value); } catch (OgnlException e) { e.printStackTrace(); } } } class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } 控制台输出:

zhangsan可以看到我们正确的取得了person对象的name属性值,该getValue声明如下:

public static <T> T getValue(String expression,Object root)throws OgnlException Convenience method that combines calls to parseExpression and getValue. Parameters: expression - the OGNL expression to be parsed root - the root object for the OGNL expression Returns: the result of evaluating the expression OGNL会根据表达式从根对象(root)中提取值。

示例:上下文环境中使用OGNL

public class OGNL1 { public static void main(String[] args) { /* 创建一个上下文Context对象,它是用保存多个对象一个环境 对象 */ Map<String , Object> context = new HashMap<String , Object>(); Person person1 = new Person(); person1.setName("zhangsan"); Person person2 = new Person(); person2.setName("lisi"); Person person3 = new Person(); person3.setName("wangwu"); /* person4不放入到上下文环境中 */ Person person4 = new Person(); person4.setName("zhaoliu"); /* 将person1、person2、person3添加到环境中(上下文中) */ context.put("person1", person1); context.put("person2", person2); context.put("person3", person3); try { /* 获取根对象的"name"属性值 */ Object value = Ognl.getValue("name", context, person2); System.out.println("ognl expression \"name\" evaluation is : " + value); /* 获取根对象的"name"属性值 */ Object value2 = Ognl.getValue("#person2.name", context, person2); System.out.println("ognl expression \"#person2.name\" evaluation is : " + value2); /* 获取person1对象的"name"属性值 */ Object value3 = Ognl.getValue("#person1.name", context, person2); System.out.println("ognl expression \"#person1.name\" evaluation is : " + value3); /* 将person4指定为root对象,获取person4对象的"name"属性,注意person4对象不在上下文中 */ Object value4 = Ognl.getValue("name", context, person4); System.out.println("ognl expression \"name\" evaluation is : " + value4); /* 将person4指定为root对象,获取person4对象的"name"属性,注意person4对象不在上下文中 */ Object value5 = Ognl.getValue("#person4.name", context, person4); System.out.println("ognl expression \"person4.name\" evaluation is : " + value5); /* 获取person4对象的"name"属性,注意person4对象不在上下文中 */ // Object value6 = Ognl.getValue("#person4.name", context, person2); // System.out.println("ognl expression \"#person4.name\" evaluation is : " + value6); } catch (OgnlException e) { e.printStackTrace(); } } } class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } 控制台输出:

ognl expression "name" evaluation is : lisi ognl expression "#person2.name" evaluation is : lisi ognl expression "#person1.name" evaluation is : zhangsan ognl expression "name" evaluation is : zhaoliu ognl.OgnlException: source is null for getProperty(null, "name") at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2296) at ognl.ASTProperty.getValueBody(ASTProperty.java:114) at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) at ognl.SimpleNode.getValue(SimpleNode.java:258) at ognl.ASTChain.getValueBody(ASTChain.java:141) at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) at ognl.SimpleNode.getValue(SimpleNode.java:258) at ognl.Ognl.getValue(Ognl.java:494) at ognl.Ognl.getValue(Ognl.java:596) at ognl.Ognl.getValue(Ognl.java:566) at com.beliefbetrayal.ognl.OGNL1.main(OGNL1.java:53) 对于使用上下文的OGNL,若不指定从哪一个对象中查找"name"属性,则OGNL直接从根对象(root)查找,若指定查找对象(使用'#'号指定,如#person1),则从指定的对象中查找,若指定对象不在上下文中则会抛出异常,换句话说就是是#person1.name形式指定查找对象则必须要保证指定对象在上下文环境中。

示例:使用OGNL调用方法

public class OGNL2 { public static void main(String[] args) { /* OGNL提供的一个上下文类,它实现了Map接口 */ OgnlContext context = new OgnlContext(); People people1 = new People(); people1.setName("zhangsan"); People people2 = new People(); people2.setName("lisi"); People people3 = new People(); people3.setName("wangwu"); context.put("people1", people1); context.put("people2", people2); context.put("people3", people3); context.setRoot(people1); try { /* 调用 成员方法 */ Object value = Ognl.getValue("name.length()", context, context.getRoot()); System.out.println("people1 name length is :" + value); Object upperCase = Ognl.getValue("#people2.name.toUpperCase()", context, context.getRoot()); System.out.println("people2 name upperCase is :" + upperCase); Object invokeWithArgs = Ognl.getValue("name.charAt(5)", context, context.getRoot()); System.out.println("people1 name.charAt(5) is :" + invokeWithArgs); /* 调用静态方法 */ Object min = Ognl.getValue("@java.lang.Math@min(4,10)", context, context.getRoot()); System.out.println("min(4,10) is :" + min); /* 调用静态变量 */ Object e = Ognl.getValue("@java.lang.Math@E", context, context.getRoot()); System.out.println("E is :" + e); } catch (OgnlException e) { e.printStackTrace(); } } } class People { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } 控制台输出:

people1 name length is :8 people2 name upperCase is :LISI people1 name.charAt(5) is :s min(4,10) is :4 E is :2.718281828459045 使用OGNL调用方法也十分简单,对于成员方法调用,只需要给出方法的名称+(),若有参数,直接写在括号内,与一般调用Java方法一致。对于静态方法的调用,需要使用如下格式:@ClassName@method,对于静态变量需要使用如下格式:@ClassName@field。

示例:使用OGNL操作集合

public class OGNL3 { public static void main(String[] args) throws Exception { OgnlContext context = new OgnlContext(); Classroom classroom = new Classroom(); classroom.getStudents().add("zhangsan"); classroom.getStudents().add("lisi"); classroom.getStudents().add("wangwu"); classroom.getStudents().add("zhaoliu"); classroom.getStudents().add("qianqi"); Student student = new Student(); student.getContactWays().put("homeNumber", "110"); student.getContactWays().put("companyNumber", "119"); student.getContactWays().put("mobilePhone", "112"); context.put("classroom", classroom); context.put("student", student); context.setRoot(classroom); /* 获得classroom的students集合 */ Object collection = Ognl.getValue("students", context, context.getRoot()); System.out.println("students collection is :" + collection); /* 获得classroom的students集合 */ Object firstStudent = Ognl.getValue("students[0]", context, context.getRoot()); System.out.println("first student is : " + firstStudent); /* 调用集合的方法 */ Object size = Ognl.getValue("students.size()", context, context.getRoot()); System.out.println("students collection size is :" + size); System.out.println("--------------------------飘逸的分割线--------------------------"); Object mapCollection = Ognl.getValue("#student.contactWays", context, context.getRoot()); System.out.println("mapCollection is :" + mapCollection); Object firstElement = Ognl.getValue("#student.contactWays['homeNumber']", context, context.getRoot()); System.out.println("the first element of contactWays is :" + firstElement); System.out.println("--------------------------飘逸的分割线--------------------------"); /* 创建集合 */ Object createCollection = Ognl.getValue("{'aa','bb','cc','dd'}", context, context.getRoot()); System.out.println(createCollection); /* 创建Map集合 */ Object createMapCollection = Ognl.getValue("#{'key1':'value1','key2':'value2'}", context, context.getRoot()); System.out.println(createMapCollection); } } class Classroom { private List<String> students = new ArrayList<String>(); public List<String> getStudents() { return students; } public void setStudents(List<String> students) { this.students = students; } } class Student { private Map<String , Object> contactWays = new HashMap<String , Object>(); public Map<String , Object> getContactWays() { return contactWays; } public void setContactWays(Map<String , Object> contactWays) { this.contactWays = contactWays; } } 控制台的输出:

students collection is :[zhangsan, lisi, wangwu, zhaoliu, qianqi] first student is : zhangsan students collection size is :5 --------------------------飘逸的分割线-------------------------- mapCollection is :{homeNumber=110, mobilePhone=112, companyNumber=119} the first element of contactWays is :110 --------------------------飘逸的分割线-------------------------- [aa, bb, cc, dd] {key1=value1, key2=value2} OGNL不仅可以操作集合对象,还可以创建集合对象,对集合操作与对属性的操作没什么不同,需要注意的是OGNL认为List与Array是一样的。使用OGNL创建List集合时使用{},创建Map对象时使用#{}。

示例:使用OGNL过滤集合与投影集合

public class OGNL4 { public static void main(String[] args) throws Exception { OgnlContext context = new OgnlContext(); Humen humen = new Humen(); humen.setName("qiuyi"); humen.setSex("n"); humen.setAge(22); humen.getFriends().add(new Humen("zhangsan" , "n" , 22)); humen.getFriends().add(new Humen("lisi" , "f" , 21)); humen.getFriends().add(new Humen("wangwu" , "n" , 23)); humen.getFriends().add(new Humen("zhaoliu" , "n" , 22)); humen.getFriends().add(new Humen("qianqi" , "n" , 22)); humen.getFriends().add(new Humen("sunba" , "f" , 20)); humen.getFriends().add(new Humen("yangqiu" , "f" , 25)); context.put("humen", humen); context.setRoot(humen); /* OGNL过滤集合的语法为:collection.{? expression} */ Object filterCollection = Ognl.getValue("friends.{? #this.name.length() > 7}", context, context.getRoot()); System.out.println("filterCollection is :" + filterCollection); System.out.println("--------------------------飘逸的分割线--------------------------"); /* OGNL投影集合的语法为:collection.{expression} */ Object projectionCollection = Ognl.getValue("friends.{name}", context, context.getRoot()); System.out.println("projectionCollection is :" + projectionCollection); } } class Humen { private String name; private String sex; private int age; private List<Humen> friends = new ArrayList<Humen>(); public Humen() { } public Humen(String name , String sex , int age) { this.name = name; this.sex = sex; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Humen> getFriends() { return friends; } public void setFriends(List<Humen> friends) { this.friends = friends; } @Override public String toString() { return "Humen [name=" + name + ", sex=" + sex + ", age=" + age + "]"; } } 控制台输出:

filterCollection is :[Humen [name=zhangsan, sex=n, age=22]] --------------------------飘逸的分割线-------------------------- projectionCollection is :[zhangsan, lisi, wangwu, zhaoliu, qianqi, sunba, yangqiu] OGNL可以对集合进行过滤与投影操作,过滤的语法为collection.{? expression},其中使用"#this"表示集合当前对象(可以与for-each循环比较)。投影的语法为collection.{expression}。投影和过滤可以看做是数据库中对表取列和取行的操作。


--------------------------------------------------------------------------------

Struts2与OGNL

Struts 2支持以下几种表达式语言:
1. OGNL(Object-Graph Navigation Language),可以方便地操作对象属性的开源表达式语言;
2. JSTL(JSP Standard Tag Library),JSP 2.0集成的标准的表达式语言;
3. Groovy,基于Java平台的动态语言,它具有时下比较流行的动态语言(如Python、Ruby和Smarttalk等)的一些起特性;
4. Velocity,严格来说不是表达式语言,它是一种基于Java的模板匹配引擎,具说其性能要比JSP好。

Struts 2默认的表达式语言是OGNL,原因是它相对其它表达式语言具有下面几大优势:
1. 支持对象方法调用,如xxx.doSomeSpecial();
2. 支持类静态的方法调用和值访问,表达式的格式为@[类全名(包括包路径)]@[方法名 | 值名],例如:@java.lang.String@format('foo %s', 'bar')或@tutorial.MyConstant@APP_NAME;
3. 支持赋值操作和表达式串联,如price=100, discount=0.8, calculatePrice(),这个表达式会返回80;
4. 访问OGNL上下文(OGNL context)和ActionContext;
5. 操作集合对象。

——————————————以上内容引用自http://www.blogjava.net/max/archive/2007/04/28/114417.html



平时使用Struts2标签时会出现一些很奇特的问题,对于OGNL不了解的人可能对问题的出现无能为力或者就算解决了问题也不知道是如何解决的。下面总结一些使用Struts2标签容易出现的困惑:

问题一:#,%{},$符号

在Struts2标签属性中经常会出现"#"或者"%{}"的符号出现,通过上面OGNL表达式基础的介绍,知道了OGNL上下文中有且仅有一个根对象。Struts2为我们定义了许多明明对象,他们分别是"ValueStack","Parameters","Session","Request", "Appliction","Attr",其中"ValueStack"被设置为上下文的根对象。访问非根对象必须加上"#"号,这就是出现"#"的原因。Struts2中的标的处理类,并不是所有都将标签的属性作为OGNL表达式来看待,有时候我们需要设置动态地值,则必须告诉标签的处理类该字符串按照OGNL表达式来处理,%{}符号的作用就是告诉标签的处理类将它包含的字符串按照OGNL表达式处理。 "$"符号用于XML文件中用于获取动态值,与%{}作用类似。

问题二:%{}符号的影响

Struts2的标签几十几百个,要记住哪一个标签的处理类将标签的属性作为OGNL表达式是一件很困难的事情,在不清楚处理类的处理方式时怎么办,%{}对于标签处理类来说,若处理类将属性值作为普通字符串则%{}符号包含的字符串当做OGNL表达式,若处理类将属性值作为OGNL表达式来处理,则直接忽略%{}符号。换句话说,不清楚处理方式的话,可以都使用%{}符号。

问题三:标签是如何获得数据

下面是ValueStack的官方描述:

ValueStack allows multiple beans to be pushed in and dynamic EL expressions to be evaluated against it. When evaluating an expression, the stack will be searched down the stack, from the latest objects pushed in to the earliest, looking for a bean with a getter or setter for the given property or a method of the given name (depending on the expression being evaluated).

大致意思:ValueStack允许保存多个bean(也就是Action),并且可以使用表达式语言获得他们。当评估一个表达式,ValueStack将会从栈顶到栈底的方向被搜索一遍,对于给定的属性名称寻找bean的getter或setter方法或寻找给定的方法。


每当一个请求到达Action时,Struts2会将Action对象推入ValueStack中。

<body> username:<s:property value="username"/><br /> -------------------诡异的分割线-------------------<br /> username:<%= ((HelloWorldAction)ActionContext.getContext().getValueStack().peek()).getUsername() %><br /> </body> 页面显示结果:

username:zhangsan -------------------诡异的分割线------------------- username:zhangsan 可以看到标签取值与用Java代码取值的结果相同,明显标签的取值方式更简练简洁。OGNL表达式"username"表示了从根对象ValueStack中取出属性username的值。它会从栈顶到栈底遍历ValueStack,直到找某一个Action中的"username"属性
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值