1. 程式人生 > >Stuts2學習筆記(1):環境搭建及Demo

Stuts2學習筆記(1):環境搭建及Demo

原始碼:

github: https://github.com/liaotuo/Struts2-Demo/tree/master/struts2-demo

環境搭建

下載struts2

官網下載:http://mirror.bit.edu.cn/apache/struts/2.3.34/struts-2.3.34-all.zip

注:本教程使用2.3.34版本

目錄結構

這裡寫圖片描述

所需基本jar包

解壓apps下一個demo能夠得到所需的基本jar包
這裡寫圖片描述

建立web專案

建立一個web專案,並將所需jar包放入WEB-INFO/lib下面(web專案無需build-path)如下圖:
這裡寫圖片描述

編寫Struts.xml配置檔案

可以直接從struts-blank demo中Copy一個struts.xml 並刪掉其中的配置,如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

</struts>

在web.xml中註冊Struts2啟動配置

往web.xml中加入如下配置

<filter>
    <filter-name>struts2</filter-name>
    <!-- 這個類全名不同版本不完全一樣 可以從struts-core.jar 中找-->
    <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>

至此環境搭建完畢,接下來建立一個demo


Demo

建立我的第一個action

package com.lt.action;

public class HelloAction {
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    /***
     * 預設的action執行方法為excute
     * @return 
     */
    public String excute() {
        this.setMsg("hello struts2...");
        return "success";
    }

    /***
     * 動態方法呼叫demo
     * @return
     */
    public String dynamic() {
        this.setMsg("hello struts2-dynamicMethod...");
        return "success";
    }
}

在struts.xml中註冊Action

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
    <!-- 常量名可以從struts-core包下org.apache.struts2 下default.properties下檢視 -->
    <!-- 配置啟用動態方法呼叫 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>
    <!-- 需要繼承自struts-default 執行預設的攔截器 -->
    <package name="basePakage" namespace="/" extends="struts-default">
        <!-- 配置action 預設method是excute可以不配置 -->
        <action name="helloAction" class="com.lt.action.HelloAction" method="execute">
             <result name="success">index.jsp</result>
        </action>
    </package>
</struts>

測試成功

注:訪問路徑需注意

這裡寫圖片描述

deault-value

  • 未指定action 預設執行的Class是ActionSupport
  • 預設執行action中的execute() 方法
  • 沒有指定result的name屬性,預設值為success

動態方法呼叫的方式

開啟常量

<!-- 配置啟用動態方法呼叫 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

這裡寫圖片描述

萬用字元配置

修改action配置

<action name="helloAction_*" class="com.lt.action.HelloAction" method="{1}">
     <result name="success">index.jsp</result>
</action>

這裡寫圖片描述