Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

排除 Struts2「There is no Action mapped for namespace」錯誤的完整檢查清單

編輯:關於 Android 程式設計

剛開始設定 Struts2 時,幾乎每個人都會遇到 There is no Action mapped for namespace / and action name 這類訊息。多數情況是細節疏漏所致,以下依發生頻率整理出排查順序。

一、struts.xml 設定有誤

這是最常見的原因。DTD 的問題網上討論很多,此處不再贅述;這裡要提的是版本問題——請確認 DTD 對應的是 2.0 而非 2.1,兩者結構有差異,建議統一採用 2.0。

其次是編碼格式。若出現中文亂碼,記得補上編碼常數:

<constant name="struts.i18n.encoding" value="GBK" />

再來是 package 段落,這裡的問題佔了大半:

  • extends 屬性:用於繼承 struts-default 或其他 package,依實際狀況填寫,但不要漏掉,否則核心功能不會被載入。
  • namespace 拼寫:專案通常會分模組,建議在練習階段就養成寫 /模組名 的習慣,方便日後擴充;若只是單純練習,寫 / 也可以,此時訪問路徑直接是 <%=request.getContextPath()%>/index.action。
  • result 路徑的斜線:<result>/r1.jsp</result> 中的開頭斜線很容易漏掉。若訪問 action 時出現「The requested resource is not available」,多半就是這個原因。

完整的設定範例:

<?xml version="1.0" encoding="UTF-8" ?>
<struts>
    <constant name="struts.i18n.encoding" value="GBK" />

    <package extends="struts-default" name="actions" namespace="/actions">
        <action name="index">
            <result>/r1.jsp</result>
        </action>
    </package>
</struts>

二、index.jsp 的問題

<%@ page language="java" contentType="text/html; charset=GB18030"
         pageEncoding="GB18030"%>
<%
    String context = request.getContextPath();
    System.out.println(context);
%>

這裡最容易出錯的是 JSP 的存放位置。Eclipse 與 MyEclipse 的目錄結構不同——使用 Eclipse EE 時,JSP 放在 WebContent,與 WEB-INF 同層。若檔案放錯位置,請求自然轉不到,這是相當常見的原因之一。

另外建議訪問時明確帶上 .action 副檔名,避免與 welcome-file 的匹配規則混淆。

三、web.xml 設定

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
         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">
    <display-name>Struts</display-name>

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

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

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

filter 段落建議直接複製上面這份,不要自行改動類別路徑——Struts2 2.x 與 1.x 的 filter 類完全不同,混用會導致請求根本進不到框架。另外 welcome-file-list 也值得檢查:工具產生的預設 web.xml 常同時帶有 index.html 與 index.htm,若它們仍存在且排在 index.jsp 之前,就會優先被導向那些不存在的檔案,請依實際情況刪除。

依上述三個方向逐項核對,這個錯誤大致都能收斂。實務上最有效的一招,是先在最小專案中把「一個 action + 一個 result」跑通,再逐步把功能加回去,如此便能快速定位是哪一處設定出了問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved