2007-09-18

dwr integration with struts2

关键字: dwr,struts2

DWR 2.0 had come with some integration with  Spring, Webwork, acegi, JSF, Struts1 and Hibernate. 

But! no for Struts2.So must copy from package  "org.directwebremoting.webwork" of DWR 2.0 Source and modify to make DWR can integration with Strtus2.The important thing is to modify DWRAction.java file; and other java file is only to modify the package reference(if  necessary).

^_^,of course, this modification is base on googling...

java 代码
 
  1. import java.io.UnsupportedEncodingException;   
  2. import java.util.HashMap;   
  3. import java.util.Map;   
  4.   
  5. import javax.servlet.ServletContext;   
  6. import javax.servlet.ServletException;   
  7. import javax.servlet.http.HttpServletRequest;   
  8. import javax.servlet.http.HttpServletResponse;   
  9.   
  10. import org.directwebremoting.util.FakeHttpServletResponse;   
  11. import org.directwebremoting.util.LocalUtil;   
  12. import org.directwebremoting.util.Logger;   
  13.   
  14.   
  15. import org.apache.struts2.ServletActionContext;   
  16. import org.apache.struts2.dispatcher.Dispatcher;   
  17. import org.apache.struts2.dispatcher.mapper.ActionMapping;   
  18.   
  19. import com.opensymphony.xwork2.ActionContext;   
  20. import com.opensymphony.xwork2.ActionInvocation;   
  21. import com.opensymphony.xwork2.ActionProxy;   
  22. import com.opensymphony.xwork2.ActionProxyFactory;   
  23. import com.opensymphony.xwork2.Result;   
  24. import com.opensymphony.xwork2.config.Configuration;   
  25. import com.opensymphony.xwork2.config.ConfigurationException;   
  26. import com.opensymphony.xwork2.util.OgnlValueStack;   
  27.   
  28.   
  29. /**  
  30.  * This class represents the entry point to all WebWork action invocations. It identifies the  
  31.  * action to be invoked, prepares the action invocation context and finally wraps the  
  32.  * result.  
  33.  * You can configure an IDWRActionProcessor through a context-wide initialization parameter  
  34.  * dwrActionProcessor that whose methods will be invoked around action invocation.  
  35.  *  
  36.  * @author  
  37.  */  
  38. public class DWRAction   
  39. {   
  40.     /**  
  41.      * The log stream  
  42.      */  
  43.     private static final Logger log = Logger.getLogger(DWRAction.class);   
  44.   
  45.     private static final String DWRACTIONPROCESSOR_INIT_PARAM = "dwrActionProcessor";   
  46.   
  47.     private static DWRAction s_instance;   
  48.   
  49.     private Dispatcher m_wwDispatcher;   
  50.   
  51.     private IDWRActionProcessor m_actionProcessor;   
  52.   
  53.     @SuppressWarnings("unchecked")   
  54.     private DWRAction(ServletContext servletContext) throws ServletException       
  55.     {       
  56.        // Dispatcher.initialize(servletContext);       
  57.         m_wwDispatcher = Dispatcher.getInstance();       
  58.         if(m_wwDispatcher==null)       
  59.         {       
  60.            m_wwDispatcher = new Dispatcher(servletContext, new HashMap());       
  61.            m_wwDispatcher.init();       
  62.            Dispatcher.setInstance(m_wwDispatcher);       
  63.         }       
  64.                
  65.         m_actionProcessor = loadActionProcessor(servletContext.getInitParameter         (DWRACTIONPROCESSOR_INIT_PARAM));       
  66.     }   
  67.   
  68.     /**  
  69.      * Entry point for all action invocations.  
  70.      *  
  71.      * @param actionDefinition the identification information for the action  
  72.      * @param params action invocation parameters  
  73.      * @param request original request  
  74.      * @param response original response  
  75.      * @param servletContext current ServletContext  
  76.      * @return an AjaxResult wrapping invocation result  
  77.      *  
  78.      * @throws ServletException thrown if the initialization or invocation of the action fails  
  79.      */  
  80.     public static AjaxResult execute(ActionDefinition actionDefinition, Map params, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) throws ServletException   
  81.     {   
  82.         initialize(servletContext);   
  83.   
  84.         return s_instance.doExecute(actionDefinition, params, request, response, servletContext);   
  85.     }   
  86.   
  87.     protected AjaxResult doExecute(ActionDefinition actionDefinition, Map params, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) throws ServletException   
  88.     {   
  89.   
  90.         FakeHttpServletResponse actionResponse = new FakeHttpServletResponse();   
  91.   
  92.         if (null != m_actionProcessor)   
  93.         {   
  94.             m_actionProcessor.preProcess(request, response, actionResponse, params);   
  95.         }   
  96.   
  97.         m_wwDispatcher.prepare(request, actionResponse);   
  98.   
  99.         ActionInvocation invocation = invokeAction(m_wwDispatcher, request, actionResponse, servletContext, actionDefinition, params);   
  100.   
  101.         AjaxResult result = null;   
  102.         if (actionDefinition.isExecuteResult())   
  103.         {   
  104.             // HINT: we have output string   
  105.             result = getTextResult(actionResponse);   
  106.         }   
  107.         else  
  108.         {   
  109.             result = new DefaultAjaxDataResult(invocation.getAction());   
  110.         }   
  111.   
  112.         if (null != m_actionProcessor)   
  113.         {   
  114.             m_actionProcessor.postProcess(request, response, actionResponse, result);   
  115.         }   
  116.   
  117.         return result;   
  118.     }   
  119.   
  120.     @SuppressWarnings("unchecked")   
  121.     protected ActionInvocation invokeAction(Dispatcher du, HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionDefinition actionDefinition, Map params) throws ServletException   
  122.     {   
  123.         ActionMapping mapping = getActionMapping(actionDefinition, params);   
  124.         Map extraContext = du.createContextMap(request, response, mapping, context);   
  125.   
  126.         // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action   
  127.         OgnlValueStack stack = (OgnlValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);   
  128.         if (null != stack)   
  129.         {   
  130.             extraContext.put(ActionContext.VALUE_STACK, new OgnlValueStack(stack));   
  131.         }   
  132.   
  133.         try  
  134.         {   
  135.             prepareContinuationAction(request, extraContext);   
  136.   
  137.             Configuration config = du.getConfigurationManager().getConfiguration();       
  138.             ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(       
  139.                     mapping.getNamespace(), mapping.getName(), extraContext, actionDefinition.isExecuteResult(), false); proxy.setMethod(actionDefinition.getMethod());   
  140.             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());   
  141.   
  142.             // if the ActionMapping says to go straight to a result, do it!   
  143.             if (mapping.getResult() != null)   
  144.             {   
  145.                 Result result = mapping.getResult();   
  146.                 result.execute(proxy.getInvocation());   
  147.             }   
  148.             else  
  149.             {   
  150.                 proxy.execute();   
  151.             }   
  152.   
  153.             return proxy.getInvocation();   
  154.         }   
  155.         catch (ConfigurationException ce)   
  156.         {   
  157.             throw new ServletException("Cannot invoke action '" + actionDefinition.getAction() + "' in namespace '" + actionDefinition.getNamespace() + "'", ce);   
  158.         }   
  159.         catch (Exception e)   
  160.         {   
  161.             throw new ServletException("Cannot invoke action '" + actionDefinition.getAction() + "' in namespace '" + actionDefinition.getNamespace() + "'", e);   
  162.         }   
  163.         finally  
  164.         {   
  165.             // If there was a previous value stack then set it back onto the request   
  166.             if (null != stack)   
  167.             {   
  168.                 request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);   
  169.             }   
  170.         }   
  171.     }   
  172.   
  173.     protected void prepareContinuationAction(HttpServletRequest request, Map extraContext)   
  174.     {   
  175. //        String id = request.getParameter(XWorkContinuationConfig.CONTINUE_PARAM);   
  176. //        if (null != id)   
  177. //        {   
  178. //            // remove the continue key from the params - we don't want to bother setting   
  179. //            // on the value stack since we know it won't work. Besides, this breaks devMode!   
  180. //            Map params = (Map) extraContext.get(ActionContext.PARAMETERS);   
  181. //            params.remove(XWorkContinuationConfig.CONTINUE_PARAM);   
  182. //   
  183. //            // and now put the key in the context to be picked up later by XWork   
  184. //            extraContext.put(XWorkContinuationConfig.CONTINUE_KEY, id);   
  185. //        }   
  186.     }   
  187.   
  188.     protected ActionMapping getActionMapping(ActionDefinition actionDefinition, Map params)   
  189.     {   
  190.         ActionMapping actionMapping = new ActionMapping(actionDefinition.getAction(), actionDefinition.getNamespace(), actionDefinition.getMethod(), params);   
  191.   
  192.         return actionMapping;   
  193.     }   
  194.   
  195.     protected AjaxTextResult getTextResult(FakeHttpServletResponse response)   
  196.     {   
  197.         DefaultAjaxTextResult result = new DefaultAjaxTextResult();   
  198.   
  199.         String text = null;   
  200.         try  
  201.         {   
  202.             text = response.getContentAsString();   
  203.         }   
  204.         catch (UnsupportedEncodingException uee)   
  205.         {   
  206.             log.warn("Cannot retrieve text output as string", uee);   
  207.         }   
  208.   
  209.         if (null == text)   
  210.         {   
  211.             try  
  212.             {   
  213.                 text = response.getCharacterEncoding() != null ? new String(response.getContentAsByteArray(), response.getCharacterEncoding()) : new String(response.getContentAsByteArray());   
  214.             }   
  215.             catch (UnsupportedEncodingException uee)   
  216.             {   
  217.                 log.warn("Cannot retrieve text output as encoded byte array", uee);   
  218.                 text = new String(response.getContentAsByteArray());   
  219.             }   
  220.         }   
  221.   
  222.         result.setText(text);   
  223.         return result;   
  224.     }   
  225.   
  226.     /**  
  227.      * Performs the one time initialization of the singleton DWRAction.  
  228.      *  
  229.      * @param servletContext  
  230.      * @throws ServletException thrown in case the singleton initialization fails  
  231.      */  
  232.     private static void initialize(ServletContext servletContext) throws ServletException   
  233.     {   
  234.         synchronized(DWRAction.class)   
  235.         {   
  236.             if (null == s_instance)   
  237.             {   
  238.                 s_instance = new DWRAction(servletContext);   
  239.             }   
  240.         }   
  241.     }   
  242.   
  243.     /**  
  244.      * Tries to instantiate an IDWRActionProcessor if defined in web.xml.  
  245.      *  
  246.      * @param actionProcessorClassName  
  247.      * @return an instance of IDWRActionProcessor if the init-param is defined or null  
  248.      * @throws ServletException thrown if the IDWRActionProcessor cannot be loaded and instantiated  
  249.      */  
  250.     private static IDWRActionProcessor loadActionProcessor(String actionProcessorClassName) throws ServletException   
  251.     {   
  252.         if (null == actionProcessorClassName || "".equals(actionProcessorClassName))   
  253.         {   
  254.             return null;   
  255.         }   
  256.   
  257.         try  
  258.         {   
  259.             Class actionProcessorClass = LocalUtil.classForName(actionProcessorClassName);   
  260.   
  261.             return (IDWRActionProcessor) actionProcessorClass.newInstance();   
  262.         }   
  263.         catch(ClassNotFoundException cnfe)   
  264.         {   
  265.             throw new ServletException("Cannot load DWRActionProcessor class '" + actionProcessorClassName + "'", cnfe);   
  266.         }   
  267.         catch(IllegalAccessException iae)   
  268.         {   
  269.             throw new ServletException("Cannot instantiate DWRActionProcessor class '" + actionProcessorClassName + "'. Default constructor is not visible", iae);   
  270.         }   
  271.         catch(InstantiationException ie)   
  272.         {   
  273.             throw new ServletException("Cannot instantiate DWRActionProcessor class '" + actionProcessorClassName + "'. No default constructor found", ie);   
  274.         }   
  275.         catch(Throwable cause)   
  276.         {   
  277.             throw new ServletException("Cannot instantiate DWRActionProcessor class '" + actionProcessorClassName + "'", cause);   
  278.         }   
  279.     }   
  280.   
  281. }  
评论
Clayz 2008-03-13
留个记号先
kkbear 2007-10-12
try this:



DWRActionUtil.execute({ 
namespace:'/ajax', 
action:'TestJS!doSomething',  
executeResult:'true' 
}, 'data', doOnJSResult, "stream...");
jiangcccc 2007-10-11
你改的这个可以用么?兄弟
为什么我只能调用action的execute方法,调用其他的方法就报错了?

DWRActionUtil.execute({
namespace:'/ajax',
action:'TestJS',
method:'doSomething',
executeResult:'true'
}, 'data', doOnJSResult, "stream...");

只要加上method:'doSomething'就会报找不到action
kkbear 2007-09-30
Hi,I think u used the wrong method.
Not DWRUtil, but is DWRActionUtil.
So copy DWRActionUtil.js from package "org.directwebremoting.webwork" of DWR 2.0 Source to ur js dir.
<script type='text/javascript' src='<%=path%>/'your js dir'/DWRActionUtil.js'></script> 
<script type='text/javascript' src='<%=path%>/dwr/interface/DwrBean.js'></script>
<script type='text/javascript' src='<%=path%>/dwr/interface/DWRAction.js'></script>
<script type='text/javascript' src='<%=path%>/dwr/engine.js'></script>
<script type='text/javascript' src='<%=path%>/dwr/util.js'></script>

And modify the method called:
function checkuser(){
DWRActionUtil.execute({namespace:'/sys', action:'login', executeResult:'true'}, 'form1', writePage);
} 
iceheartboy 2007-09-29
哥们,我按照你的做法,没有成功啊!
我的dwr.xml
<create creator="none" javascript="DWRAction">
<param name="class"
value="org.directwebremoting.struts2.DWRAction" />
<include method="execute" />
</create>

<convert converter="bean"
match="org.directwebremoting.struts2.ActionDefinition">
<param name="include"
value="namespace,action,method,executeResult" />
</convert>

<convert converter="bean"
match="org.directwebremoting.webwork.AjaxResult" />

<convert converter="bean"
match="action.bywangchb.Login" />
我的web.xml
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<!--
<display-name>DWR Servlet</display-name>
-->
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>exposeInternals</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
我的jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type='text/javascript' src='<%=path%>/dwr/interface/DwrBean.js'></script>
<script type='text/javascript' src='<%=path%>/dwr/interface/DWRAction.js'></script>
<script type='text/javascript' src='<%=path%>/dwr/engine.js'></script>
<script type='text/javascript' src='<%=path%>/dwr/util.js'></script>

<title>Struts 2</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<script language="javascript">
//function checkuser(){
// DWRAction.execute('/sys/login', 'form1', 'writePage');
//}
function checkuser(){
DWRAction.execute({namespace:'/sys', action:'login', executeResult:'true'}, 'form1', writePage);
}
function writePage(msg){
DWRUtil.setValue('person_ls', msg);
}
</script>
<body>
<form method="post" name="form1" action="" id="form1">
<p align="center">用户名:<input type="text" name="name" id="name"></p>
<p align="center">密 码:<input type="password" name="pass" id="password"></p>
<p> </p>
<p align="center"><input type="button" value="登陆" onclick="checkuser()"></p>
<div id="result"></div>
<div id="person_ls"></div>
</form>
</body>
</html>

里面两种 调用action的方法都报错
Missing I18N string: MapConverter.FormatError. Params: [{]

郁闷 有时间能帮忙看看么?大侠
发表评论

您还没有登录,请登录后发表评论

kkbear
搜索本博客
最近加入圈子
最新评论