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

Struts2 頁面取值的原理與 ValueStack 的實際用法

Struts 2 把 Action 的所有輸出資訊都收進一個名為 ValueStack 的物件裡,而頁面端可以透過 OGNL 表達式輕鬆把資料取出來。理解這層機制,除錯與自訂取值邏輯都會順手很多。

ValueStack 是什麼

它的行為有點像 Map,但比 Map 更強大:查詢時可以直接丟入運算式,而不只是 key。Action 中宣告的每個屬性,都被視為 ValueStack 上一個可被表達式存取的值。在伺服器端要拿到這個物件,可以從 request 範圍取出:

// 取得封裝輸出資訊的 ValueStack 物件
ValueStack vs = (ValueStack) request.getAttribute("struts.valueStack");

// 呼叫 findValue 取得 books 屬性值
String[] books = (String[]) vs.findValue("books");

web.xml:註冊核心 Filter

<?xml version="1.0" encoding="GBK"?>
<web-app xmlns="https://java.sun.com/xml/ns/javaee"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="https://java.sun.com/xml/ns/javaee
         https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <!-- 定義 Struts 2 的核心控制器 FilterDispatcher -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <!-- FilterDispatcher 負責初始化 Struts 2 並處理所有 HTTP 請求 -->
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

struts.xml:Action 與結果的對應

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
    "https://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <package name="strutsqs" extends="struts-default">

        <action name="login" class="lee.LoginAction">
            <result name="error">/error.jsp</result>
            <result name="success">/welcome.jsp</result>
        </action>

        <action name="getBooks" class="lee.GetBooksAction">
            <result name="login">/login.jsp</result>
            <result name="success">/showBook.jsp</result>
        </action>

    </package>
</struts>

GetBooksAction.java

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class GetBooksAction implements Action {
    // 此屬性不用於接收請求參數,而是用來裝要輸出到 JSP 的資料
    private String[] books;

    public void setBooks(String[] books) {
        this.books = books;
    }

    public String[] getBooks() {
        return books;
    }

    public String execute() throws Exception {
        String user = (String) ActionContext.getContext().getSession().get("user");
        if (user != null && user.equals("crazyit")) {
            BookService bs = new BookService();
            setBooks(bs.getLeeBooks());
            return SUCCESS;
        } else {
            return LOGIN;
        }
    }
}

BookService.java

public class BookService {
    // 以陣列模擬從資料庫取出的資料
    private String[] books = new String[] {
        "瘋狂Java講義",
        "輕量級Java EE企業應用實戰",
        "瘋狂Ajax講義",
        "瘋狂XML講義",
        "Struts 2權威指南"
    };

    public String[] getLeeBooks() {
        return books;
    }
}

showBooks.jsp:兩種取值方式

頁面上可以直接用 OGNL 寫 <s:property value="books"/> 之類的標籤,也可以像下面這樣以程式碼取出 ValueStack 再自行迭代,後者對理解底層運作特別有幫助。

<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ page import="java.util.*,com.opensymphony.xwork2.util.*" %>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
    <title>圖書</title>
</head>
<body>
<table border="1" width="360">
    <caption>圖書</caption>
    <%
        // 取得封裝輸出資訊的 ValueStack 物件
        ValueStack vs = (ValueStack) request.getAttribute("struts.valueStack");
        // 取出 books 屬性值
        String[] books = (String[]) vs.findValue("books");
        // 迭代輸出全部圖書
        for (String book : books) {
    %>
    <tr>
        <td>書名:</td>
        <td><%= book %></td>
    </tr>
    <% } %>
</table>
</body>
</html>

釐清 ValueStack 的存在,就能理解為什麼 Action 只要準備好 getter,頁面不必額外設定就能取到值——這正是 Struts 2 表達式綁定的基礎。

Copyright © Linux教程網 All Rights Reserved