Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Struts 2 的表達式語言與 OGNL 中 #、%、$ 的用法

Struts 2 支援的表達式語言

  1. OGNL(Object-Graph Navigation Language):能方便地操作物件屬性的開源表達式語言。
  2. JSTL(JSP Standard Tag Library):JSP 2.0 整合的標準表達式語言。
  3. Groovy:基於 Java 平台的動態語言,具備 Python、Ruby、Smalltalk 等動態語言的部分特性。
  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 context 與 ActionContext。
  5. 能操作集合物件。

OGNL 的實際用法

OGNL 通常與 Struts 2 標籤搭配使用,例如 <s:property value="xx" />。大家最常卡住的是 #、%、$ 這三個符號。

先建立名為 Struts2_OGNL 的 Web 專案並配置開發環境。許多人在使用 Struts 2 時遇到亂碼問題,這類問題成因複雜、涉及多層知識,網路上已有大量討論。實務上只要多留意,避免並不難:亂碼多半源於編碼與解碼方式不一致,建議把各處編碼統一設為 UTF-8,例如:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>

另外,在 web.xml 中配置 ActionContextCleanUp 過濾器:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
    xmlns="https://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://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. 存取 OGNL context 與 Action context,# 相當於 ActionContext.getContext()。ActionContext 中幾個常用屬性如下:
    名稱作用範例
    parameters包含當前 HTTP 請求參數的 Map#parameters.id[0] 相當於 request.getParameter("id")
    request包含當前 HttpServletRequest 屬性的 Map#request.userName 相當於 request.getAttribute("userName")
    session包含當前 HttpSession 屬性的 Map#session.userName 相當於 session.getAttribute("userName")
    application包含 ServletContext 屬性的 Map#application.userName 相當於 application.getAttribute("userName")
    attr依 request > session > application 順序查閱屬性#attr.userName 會依序在三個 scope 中尋找,找到即止
  2. 過濾與投影(projecting)集合,如 books.{?#this.price < 100},作用是從集合中篩出價格低於 100 的項目。
  3. 構造 Map,如 #{'foo1':'bar1', 'foo2':'bar2'}。

至於 % 與 $:% 用於強制求值,常寫在 %{...} 中,當屬性名稱本身可能與字串混淆時用來明確表達「這裡要算」;$ 則主要出現在設定檔與國際化資源中,如 ${...} 形式的佔位符。三者分工不同,混用是初學者最常踩的坑。

Copyright © Linux教程網 All Rights Reserved