Struts 2中的表达式语言
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>
“#”主要有三种用途:
- 访问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'}。
|
评论暂时关闭