在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(飞云小侠) 阅读(849) 评论(0)  编辑  收藏 所属分类: WEB


只有注册用户登录后才能发表评论。


网站导航:
 
<2005年8月>
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

公告

文章发布许可
创造共用协议:署名,非商业,保持一致

我的邮件
cnscud # gmail


常用链接

留言簿(15)

随笔分类(113)

随笔档案(103)

相册

友情链接

技术网站

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜