首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Struts 2.1.6 實戰教程(一):環境搭建與首個零配置範例

     編輯:Java 相關知識

本系列教程將帶您從零開始搭建 Struts 2.1.6 開發環境,並通過一個極簡的 HelloWorld 範例,體驗 Convention Plugin 帶來的「零 XML 配置」開發模式。

開發環境準備

  1. Struts 2.1.6:官網下載 struts-2.1.6-all.zip
  2. Eclipse for Java EE (3.4/3.5+):Eclipse 下載頁
  3. JDK 6.0 與 Tomcat 6.0:自行安裝配置
  4. JSTL 標準標籤庫:建議下載 jstl.jar、standard.jar 放入專案 lib

建立動態 Web 專案

在 Eclipse 中新建 Dynamic Web Project,命名為 SimpleWeb。將 Struts 解壓後 lib 目錄下的核心 JAR 複製至專案 WebContent/WEB-INF/lib:

xwork-2.1.2.jar
struts2-core-2.1.6.jar
struts2-convention-plugin-2.1.6.jar
ognl-2.6.11.jar
freemarker-2.3.13.jar
commons-logging-1.0.4.jar
commons-fileupload-1.2.1.jar
jstl.jar / standard.jar (JSTL)

配置 web.xml 接入 Struts 2

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xmlns="https://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <display-name>SimpleWeb</display-name>
    <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>
</web-app>

約定目錄結構與首個 JSP

在 WEB-INF 下建立 content 目錄(固定命名),專門存放 JSP。新建 hello.jsp:

<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>Hello Simple</body></html>

關鍵驗證:.action 與無副檔名訪問

啟動 Tomcat,嘗試訪問:

  • https://localhost:8080/SimpleWeb/hello.jsp → 404 錯誤(受保護資源)
  • https://localhost:8080/SimpleWeb/hello.action 或 /hello → 成功顯示 hello.jsp

這正是 Struts 2.1.6 Convention Plugin 的威力:預設將 WEB-INF/content/ 下的 JSP 映射為同名 Action。

編寫首個 Action 類

在 cn.simple.action 建立 HelloAction:

package cn.simple.action;
import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
    @Override
    public String execute() throws Exception {
        System.out.println("HelloAction execute ...");
        return SUCCESS;
    }
}

再次訪問 /hello.action,控制台輸出確認 Action 被調用,頁面轉發至 hello.jsp。

揭秘:零配置背後的默認約定

上述行為等價於以下顯式註解配置:

@Results({
    @Result(name = "success", location = "hello.jsp", type = "dispatcher")
})
public class HelloAction extends ActionSupport { ... }
  • name="success" 對應 execute() 返回 SUCCESS
  • location="hello.jsp" 目標視圖
  • type="dispatcher" 請求轉發(保留 Request 屬性)

對比 type="redirect" 重定向(不保留 Request,地址欄變更),兩者差異同 Servlet 的 forward vs sendRedirect。

核心啟示:struts2-convention-plugin-2.1.6.jar 依據「類名/方法名/返回值」自動推導映射,實現真正的零配置。詳細規則請見官方文檔。

環境搭建與首個範例完成,下一篇將深入註解驅動的表單處理與驗證機制,敬請期待!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved