struts2:圖解action之HelloWorld示范(從action轉到JSP)


雖然Struts 2.x的Action在技術上不需要實現任何接口或繼承任何類型,但是,大多情況下我們都會出於方便的原因,使Action類繼承com.opensymphony.xwork2.ActionSupport類,並重載(Override)此類里的String execute()方法以實現相關功能。

本文是一個HelloWorld級別的action示范程序。

1. 修改web.xml

    <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>

加入上述代碼的作用是添加過濾器,攔截所有請求,將由struts來處理;具體由下面的struts.xml配置決定。

2. 創建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.action.extension" value="action"></constant>
</struts>

注意:

  • 此文件存放於WEB-INF/classes目錄下面。
  • 最后一行為我本機環境加入的,含義是只攔截后綴為action的請求。

3. 在struts.xml配置文件中注冊Action和result

    <package name="myStruts" extends="struts-default">
            <action name="hello" class="com.clzhang.ssh.demo.action.HelloAction"> 
                <result>/ssh/demo1/hello.jsp</result> 
            </action>      
    </package>

action的name決定調用時的名稱;class為實現類名;result的值為action執行完成后轉向何頁面。如果沒有為result指定name名稱,默認值為success

4. 創建action處理類

package com.clzhang.ssh.demo.action;

import java.util.Date;
import java.text.SimpleDateFormat;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
    private String message;

    public String getMessage() {
        return message;
    }

    @Override
    public String execute() {
        message = "Hello there, now is: "
                + new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date());

        return SUCCESS;
    }
}

關於ActionSupport類的更多內容,請參考:http://struts.apache.org/release/2.0.x/struts2-core/apidocs/index.html?overview-summary.html

5. 創建顯示JSP文件

<%@page contentType="text/html; charset=UTF-8"%> 
<%@taglib prefix="s" uri="/struts-tags"%> 
<html> 
<head> 
    <title>Hello there!</title> 
</head> 
<body> 
    <h2><s:property  value="message"/></h2> 
</body> 
</html> 

JSP文件中用到了struts標簽,以后的章節中會詳細描述。

6. 打開IE,測試

輸入地址:http://127.0.0.1:8080/st/hello.action,回車結果為:

Hello there, now is: 2013-11-18 11:13

 

圖解:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM