Struts2中自定義的Result

jopen 9年前發布 | 22K 次閱讀 Struts2 Web框架

引言

所謂自定義Result,就是由我們自行開發Result,而不是使用由Struts2預定義的result。
在實際的開發中使用自定義的result機會不大,因為常見的各種頁面展示技術,都有struts2給我們做的比較好好的。

自定義的Result

觀看Result的源碼如下:

public interface Result extends Serializable {

/**
 * Represents a generic interface for all action execution results.
 * Whether that be displaying a webpage, generating an email, sending a JMS message, etc.
 *
 * @param invocation  the invocation context.
 * @throws Exception can be thrown.
 */
public void execute(ActionInvocation invocation) throws Exception;

}</pre>

我們可以看到是一個接口,并且只有一個方法,那我們自定義的餓時候需要實現這個接口。

public class MyResult implements Result {

public void execute(ActionInvocation invocation) throws Exception {
    System.out.println("要處理的Result字符串是"+invocation.getResultCode());
}

}</pre>

可以看到,我們可以通過ActionInvocation 去獲取ActionContext,在ActionContext里邊封裝著所需要的值。

然后我們需要在struts2的配置文件中進行配置和使用:

<struts>
    <package name="helloworld" extends="struts-default">
        <result-types>
            <result-type name="MyResult" class="com.lc.action.MyResult" default="false">
            </result-type>
        </result-types>
        <action name="loginAction" class="com.lc.action.LoginAction">
            <result name="toWelocome" type="MyResult">/welcome.jsp</result>
        </action>
    </package>
</struts>  

標簽里邊的就是我們配置的一個自定義的result,然后我們在action中使用的時候是通過type=”MyResult”進行使用的。

到此一個自定義的result完成。


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!