在WebWork中實現自己的Result Type

          除經特別注明外,本站文章版權歸JScud Develop團隊或其原作者所有.
          轉載請注明作者和來源.  scud(飛云小俠)    歡迎訪問 JScud Develop



          我在項目中經常用到這樣的功能:例如添加完一個文章,我通常會提示用戶"操作完成",然后轉向到文章列表頁面或者文章詳情頁面.以前的做法是使用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,很簡單,不是嗎?
           

          posted on 2005-08-22 13:13 Scud(飛云小俠) 閱讀(873) 評論(0)  編輯  收藏 所屬分類: WEB

          <2005年8月>
          31123456
          78910111213
          14151617181920
          21222324252627
          28293031123
          45678910

          導航

          統計

          公告

          文章發布許可
          創造共用協議:署名,非商業,保持一致

          我的郵件
          cnscud # gmail


          常用鏈接

          留言簿(15)

          隨筆分類(113)

          隨筆檔案(103)

          相冊

          友情鏈接

          技術網站

          搜索

          積分與排名

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 上杭县| 纳雍县| 简阳市| 冕宁县| 榆社县| 郎溪县| 绥江县| 江北区| 南木林县| 汝城县| 洛阳市| 繁峙县| 西藏| 丹巴县| 鹰潭市| 衡南县| 万荣县| 雅江县| 康保县| 平塘县| 外汇| 怀宁县| 乳山市| 库车县| 平陆县| 丰县| 宜州市| 习水县| 陆良县| 大关县| 独山县| 新兴县| 玛曲县| 祥云县| 弥勒县| 辉县市| 无锡市| 印江| 梧州市| 九江市| 景宁|