Struts 2 的開發環境設定,所需最低的要求為:

1. Servlet API 2.4
2. JSP API 2.0
3. Java 5

可以在 http://struts.apache.org/downloads.html 此下載所需的 Struts 2 所有開發套件,在此使用 Struts 2.3.15.2 ("best available")。

在此建議的 IDE 介面為 Eclipse IDE for Java and Report Developers Eclipse IDE for Java and Report Developers,下載後解壓於 D:\Progs\eclipse ; WEB Server 可以使用 Apache Tomcat v7.0.42 ,下載後解壓於C:\AppServ\apache-tomcat-7.0.42 ; Java JDK 1.6 或 1.7 版,下載後執行安裝。接下來就直接執行 D:\Progs\eclipse\eclipse.exe 即可啟動 Eclipse IDE 開發環境。

Step 1: 首先要在 Eclipse IDE 開發環境建立一個專案 struts2_test:

struts2-sample-project.png  

整個專案的程式擺放配置如下圖:

struts2-sample.png  

Step 2: 在此專案的 WEB-INF 下建立一個 web.xml 來定義此專案起動時的執行方式

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Struts Blank</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.html</welcome-file>
    </welcome-file-list>

</web-app>

Step 3: 於Java Source 下建立 Struts 2 Action 的規則檔: 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>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">

        <default-action-ref name="index" />

        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>

        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        </global-exception-mappings>

        <action name="index">
            <result type="redirectAction">
                <param name="actionName">HelloWorld</param>
                <param name="namespace">/example</param>
            </result>
        </action>
    </package>
    
    <!-- Add packages here -->    
    <include file="example.xml"/>
    <include file="test.xml"/>
</struts>

注意,可以使用Struts 2.3.15.2 中的 struts2-blank 的專案來作初始設定。這裡建立一個 test 的 package 測試,所以要將 test.xml 檔案含括進來。test.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>
    <package name="test" namespace="/test" extends="struts-default">
        
        <action name="Hello" class="com.test.Hello">
            <result name="success">/test/Hello.jsp</result>
        </action>
        <action name="UserLogin_*" method="{1}" class="com.test.UserLoginAction">
            <result name="sign_on">/test/userLogin.jsp</result>
            <result name="input">/test/userLogin2.jsp</result>  => input 是 struts2 的預設值,即是 http://localhost:8080/struts2_test/test/UserLogin_input 會指向 /test/userLogin2.jsp 這個檔案
            <result name="success">/test/userLoginResult.jsp</result>
        </action>
        
    </package>    
    
</struts>

 Step 3:將所需 Struts2 的 JAR 檔放在 WEB-INF/lib 目錄下:

asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
commons-fileupload-1.3.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
log4j-1.2.17.jar
ognl-3.0.6.jar
struts2-core-2.3.15.2.jar
xwork-core-2.3.15.2.jar

Step 4: 先建立一個顯示 "Hi Hello Struts 2!!"  的 Hello.jsp 頁面,其中"Hello Struts 2!!"為要取得的message。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello Struts 2</title>
</head>
<body>
  Hi <s:property value="message" />
</body>
</html>

  Step 5: Hello.jsp 頁面裡要取得 message 的變數,在 test.xml 控制檔中已宣告對應的 class="com.test.Hello" ,所以要建立取得此 message 的方法:getMessage(),檔案為 Hello.java ,package 為 com.test

package com.test;

public class Hello {
    public String getMessage(){
        return "Hello Struts 2!!";
    }
    
    public String execute(){
        return "success";
    }
}

注意:struts2 預設回應的方法為 execute() ,只要填入 return "success" 即可在 Apache Tomcate 中執行 http://localhost:8080/struts2_test/test/Hello 。

 

建立一個使用者登入作業範例:

step 1:建立 userLogin2.jsp

還記得在 test.xml 中我們有一個設定<result name="input">/test/userLogin2.jsp</result>  => input 是 struts2 的預設值,即是 http://localhost:8080/struts2_test/test/UserLogin_input 會指向 /test/userLogin2.jsp 這個檔案,內容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Login Form Using taglib </title>
</head>
<body>

<s:form action="UserLogin">
    <s:textfield key="loginName" />
    <s:password key="password" />
    <s:submit />
</s:form>

</body>
</html>

 Step 2:建立對應的 ActionForm class="com.test.UserLoginAction"

package com.test;

import com.opensymphony.xwork2.ActionSupport;

public class UserLoginAction extends ActionSupport {
    
    private String loginName;
    private String password;
    
    public String getLoginName() {
        return loginName;
    }
    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String execute() throws Exception {
        if (isInvalid(getLoginName()))
            return INPUT ;
        if(isInvalid(getPassword()))
            return "sign_on";
        
        return SUCCESS; // "success";
    }
    
    private boolean isInvalid(String str){
        return ( str==null || str.length()==0 );
    }
    
    @Override
    public void validate() {
        // TODO Auto-generated method stub
        super.validate();
        if (isInvalid(getLoginName()))
            this.addFieldError("loginName", "Login Name was required");
        
    }
    
}

 Step 3:對輸入欄位加入判斷

在 Struts2 要對欄位加入偵錯判斷的方法有二個,一個是覆寫 validate() 的方法,在此方法裡加入  this.addFieldError("loginName", "Login Name was required"); ,第二種方法為建立一個檔案為 程式名-validation.xml 的檔案,如: UserLoginAction-validation.xml,內容如下:

<!DOCTYPE validators PUBLIC
        "-//Apache Struts//XWork Validator 1.0.2//EN"
        "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">

<validators>
    <field name="loginName">
        <field-validator type="requiredstring">
            <message key="requiredstring"/>
        </field-validator>
    </field>
    <field name="password">
        <field-validator type="requiredstring">
            <message key="requiredstring"/>
        </field-validator>
    </field>
</validators>

Step 4:建立多國語言判斷

Struts2 是可以支援多國語言的,但您必需使用 struts-tags 且在輸入欄位的 From 裡使用 key 值,如  <s:textfield key="loginName" /> ,多國語言的檔名為 package.properties ,預設是 US 。內容如下:

password = Password
loginName = Login Name

 PS: Eclipse 的多國語言的編輯器可以從 http://sourceforge.net/projects/eclipse-rbe/ 下載 ResourceBundleEditor_v0.8.0.zip ,解壓後放在 D:\Progs\eclipse\plugins 目錄下,重新起動 Eclipse 就可以了。

 參考:

http://struts.apache.org/release/2.2.x/docs/message-resource-files.html

 

arrow
arrow
    文章標籤
    java struts2
    全站熱搜

    MIS 發表在 痞客邦 留言(0) 人氣()