在WebWork中實現自己的Result Type

來源:互聯網
上載者:User
飛雲小俠 2005-7-27  http://www.jscud.com 轉載請註明作者

我在項目中經常用到這樣的功能:例如添加完一個文章,我通常會提示使用者"操作完成",然後轉向到文章列表頁面或者文章詳情頁面.以前的做法是使用WebWork本身的dispatcher結果類型,設定結果頁面為資訊提示頁面,在程式中設定目標頁面和提示資訊.這樣雖然也可以完成我的目標,但是目標頁面是在程式裡面寫死的,無法放在配置裡.

這幾天研究了一下WebWork的Result Type,發現寫一個新的Result Type很容易,於是誕生了我的一個新的Result Type:

功能:資訊提示並轉向到目標頁面
流程:在Action中設定提示資訊(當然也可以改到設定檔裡,但是配置起來略麻煩,所以還是寫在程式裡了),然後使用我的結果類型msgto,在設定檔裡面配置目標頁面.

代碼如下

1.頁面資訊提示類(包含頁面提示資訊和目標頁面,停留時間)

 

 
 package com.jscud.www.support.web;
 
 
 /*
  * Created Date  2004-11-23
  *
  */
 
 /**
  * 用於頁面提示的資訊類.
  *
  * @author scud
  * 
  */
 public class PageMessage
 {
     /**標題*/
     private String msgTitle;
 
     /**內容體*/
     private String msgContent;
 
     /**要轉向到的網址*/
     private String msgToURL;
 
     /**停留時間*/
     private int msgToTime = 1 ;
 
    
     public String getMsgContent()
     {
         return msgContent;
     }
 
     public void setMsgContent(String msgContent)
     {
         this.msgContent = msgContent;
     }
 
     public String getMsgTitle()
     {
         return msgTitle;
     }
 
     public void setMsgTitle(String msgTitle)
     {
         this.msgTitle = msgTitle;
     }
 
     public int getMsgToTime()
     {
        
         return msgToTime;
     }
 
     public void setMsgToTime(int msgToTime)
     {
         this.msgToTime = msgToTime;
     }
 
     public String getMsgToURL()
     {
         return msgToURL;
     }
 
     public void setMsgToURL(String msgToURL)
     {
         this.msgToURL = msgToURL;
     }
 }

 
 
 
2."msgto" Result Type ,借鑒了WebWork本身的幾個ResultType,部分代碼是copy過來的

 

 package com.jscud.www.support.web;
 
 //import com.jscud.util.LogMan;
 import com.opensymphony.webwork.config.Configuration;
 import com.opensymphony.webwork.dispatcher.ServletDispatcher;
 import com.opensymphony.webwork.dispatcher.WebWorkResultSupport;
 
 import com.opensymphony.webwork.ServletActionContext;
 import com.opensymphony.xwork.ActionContext;
 import com.opensymphony.xwork.ActionInvocation;
 import com.opensymphony.xwork.util.OgnlValueStack;
 
 import javax.servlet.RequestDispatcher;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
 /*
  * Created on 2005-7-26
  *
  */
 
 /**
  * WebWork Result Type for "msgto".
  *
  * Message Hint to User then Refresh to another Page.
  *
  * @author scud.
  *
  */
 public class ServletMessageToResult extends WebWorkResultSupport
 {
 
     //~ Static fields/initializers /////////////////////////////////////////////
 
     private static final String DefaultMessagePage = "/WEB-INF/public/page/msgto.jsp";
 
     protected String messagePage;
    
     protected boolean prependServletContext = true;
 
 
     //~ Methods ////////////////////////////////////////////////////////////////
 
     public void setMessagePage(String sPagePath)
     {
         this.messagePage = sPagePath;
     }
 
     public String getMessagePage()
     {
         if (null == messagePage)
         {
             if (Configuration.isSet("jscud.page.messageto"))
             {
                 this.messagePage = Configuration.getString("jscud.page.messageto");
             }
             else
             {
                 this.messagePage = DefaultMessagePage;
             }
         }
 
         return messagePage;
     }
 
    
     /**
      * Sets whether or not to prepend the servlet context path to the redirected URL.
      *
      * @param prependServletContext <tt>true</tt> to prepend the location with the servlet context path,
      *                              <tt>false</tt> otherwise.
      */
     public void setPrependServletContext(boolean prependServletContext) {
         this.prependServletContext = prependServletContext;
     }
    
     /**
      * Dispatches to the Message Page. Does its forward via a RequestDispatcher. If the
      * dispatch fails a 404 error will be sent back in the http response.
      *
      * @param finalLocation the location to dispatch to.
      * @param invocation    the execution state of the action
      * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
      *                   HTTP request.
      */
     public void doExecute(String finalLocation, ActionInvocation invocation)
             throws Exception
     {
         String messageLocation = getMessagePage();
 
         HttpServletRequest request = ServletActionContext.getRequest();
         HttpServletResponse response = ServletActionContext.getResponse();
 
         RequestDispatcher dispatcher = request.getRequestDispatcher(messageLocation);
 
         // if the view doesn't exist, let's do a 404
         if (dispatcher == null)
         {
             response.sendError(404, "message page '" + messageLocation + "' not found");
 
             return;
         }
 
         request.setAttribute("webwork.view_uri", messageLocation);
         request.setAttribute("webwork.request_uri", request.getRequestURI());
 
         //set refresh target url
         if (isPathUrl(finalLocation))
         {
             if (!finalLocation.startsWith("/"))
             {
                 String actionPath = request.getServletPath();
                 String namespace = ServletDispatcher
                         .getNamespaceFromServletPath(actionPath);
 
                 if ((namespace != null) && (namespace.length() > 0))
                 {
                     finalLocation = namespace + "/" + finalLocation;
                 }
                 else
                 {
                     finalLocation = "/" + finalLocation;
                 }
             }
 
             // if the URL's are relative to the servlet context, append the servlet context path
             if (prependServletContext && (request.getContextPath() != null)
                     && (request.getContextPath().length() > 0))
             {
                 finalLocation = request.getContextPath() + finalLocation;
             }
 
             finalLocation = response.encodeRedirectURL(finalLocation);
         }
 
         //LogMan.debug("Refreshing to finalLocation " + finalLocation);
        
         //設定屬性
         OgnlValueStack stack = ActionContext.getContext().getValueStack();
        
         PageMessage aPageMessage = (PageMessage)stack.findValue("pagemessage",PageMessage.class);
        
         if(null!=aPageMessage)
         {
             aPageMessage.setMsgToURL(finalLocation);
         }
        
         dispatcher.forward(request, response);
     }
 
     //copy from ServletRedirectResult
     private static boolean isPathUrl(String url)
     {
         // filter out "http:", "https:", "mailto:", "file:", "ftp:"
         // since the only valid places for : in URL's is before the path specification
         // either before the port, or after the protocol
         return (url.indexOf(':') == -1);
     } 
 }
 

 
3.資訊提示頁面

 預設為/WEB-INF/public/page/msgto.jsp,可以在webwork.properties裡面配置"jscud.page.messageto",還可以通過設定檔配置.
 
 可以根據自己需要更改頁面內容.
 
 

 <%@ page contentType="text/html; charset=GBK" %>
 <%@ taglib uri="webwork" prefix="ww" %>
 
 <html>
 <head>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
 <meta http-equiv="expires" content="0">
 
 <meta http-equiv="Content-Type" content="text/html; charset=GBK">
 
 <meta http-equiv="refresh" content="<ww:property value="pagemessage.msgToTime" />;URL=<ww:property value="pagemessage.msgToURL" />">
 
 <title><ww:property value="pagemessage.msgTitle" /></title>
 </head>
 <body >
 <div align=center>
 <table width=90% border="0" cellspacing="0" cellpadding="0" align="center" bgcolor=#ffffff>
   <tr valign="top">
     <td width="2">        
     </td>
     <td width="5"></td>
     <td colspan="3">
 <center><br><br>
 <table align="center" border="0" cellpadding="5" cellspacing="0" width="100%">
 <tbody>
 <tr>
 <td><ww:property value="pagemessage.msgTitle" />
 <hr noshade size="1" color="#808000">
 </td>
 </tr>
 <tr>
 <td><ww:property value="pagemessage.msgContent" /><br><br><br>
 請稍後......<br>
 </td>
 </tr>
 </tbody>
 </table>
 </center>
 
     </td>
   </tr>
 </table>
 
 </div>
 </body>
 </html>

 
 
 
4.配置樣本

  

  <result-types>
   <result-type name="msgto" class="com.jscud.www.support.web.ServletMessageToResult" />
  </result-types> 

 <action name="doAddCata" class="catagoryAction" method="doSet">
   <result name="input" type="dispatcher">
    <param name="location">/WEB-INF/jsp/news/catagory_add.jsp</param>
   </result>
   <result name="success" type="msgto">
    <param name="location">/news/admin/admin.jspa</param>
   </result>
  </action> 

   

5.Action中的程式碼範例

 

     /**
     * 增加/編輯類別
     *
     * @return 結果
     */
    public String doSet()
    {
        //輸入介面
        if (null == catagory)
        {
            return INPUT;
        }

        catagoryManager.updateCatagory(getCatagory(), getWork());
            //return goException("設定分類時發生了錯誤",ex);

        setPageMessageProp("操作成功", "操作成功");

        return SUCCESS;
    }

 
 
 
 以下代碼放在基礎Action裡:(自己要做適當修改)
 

    /**
     * 設定資訊提示的內容.
     *
     * @param sTitle
     * @param sHintMsg
     */
    protected void setPageMessageProp(String sTitle, String sHintMsg)
    {
        PageMessage apm = new PageMessage();

        if ((null == sTitle) || (sTitle.equals("")))
        {
            sTitle = getText("core.errorhint.title.default");
        }

        apm.setMsgTitle(sTitle);
        apm.setMsgContent(sHintMsg);

        setPagemessage(apm);
    }

    /**
     * 設定資訊提示的參數.(轉向)
     *
     * @param sTitle
     * @param sHintMsg
     * @param toURL
     * @param nToTime
     */
    protected void setPageMessageProp(String sTitle, String sHintMsg,int nToTime)
    {
        PageMessage apm = new PageMessage();

        if ((null == sTitle) || (sTitle.equals("")))
        {
            sTitle = getText("core.errorhint.title.default");
        }

        apm.setMsgTitle(sTitle);
        apm.setMsgContent(sHintMsg);
        //apm.setMsgToURL(toURL);
        apm.setMsgToTime(nToTime);

        setPagemessage(apm);
    }

    public PageMessage getPagemessage()
    {
        return pagemessage;
    }

    public void setPagemessage(PageMessage pagemessage)
    {
        this.pagemessage = pagemessage;
    }
 
  

 

 
 
ok,很簡單,不是嗎?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.