服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

ajax、struts、spring的无缝结合

zhipingch 原创

    去年初,正好负责一个医药信息系统的设计开发,架构设计时,采用struts+jdbc(自定义采用适配器模式封装了hashmap动态vo实现的持久层)。后来ajax热潮兴起,正好系统中有很多地方需要和服务器端交互数据,如采购销售系统中的订单头/订单明细等主从表结构的维护。
    [color=blue]数据交互过程[/color],我们考虑采用xml来组织数据结构,更新/保存:前台封装需要的xml,通过ajax提交---〉action解析xml ---〉改造原有的持久层实现xml持久化;
    查询时:持久层根据实际需要返回xml,document对象,---〉action 处理 --〉前台自己封装js库来解析xml,并刷新部分页面。

    ajax:已经有很多方法实现跨浏览器的方式,这里只介绍最简单的方式,同步模式下提交xmlstr给action(*.do)。

  1. /**
  2.  * 将数据同步传递给后台请求url
  3.  *  @return 返回xmlhttp 响应的信息
  4.  *  @param-url = '/web/module/xxx.do?p1=yy&p2=rr';
  5.  *  @param-xmlstr:xml格式的字符串 <data><xpath><![cdata[数据信息]]></xpath></data>
  6.  * @author zhipingch
  7.  * @date 2005-03-17
  8.  */
  9. function senddata(urlstr, xmlstr) {
  10.     var xmlhttp = new activexobject("microsoft.xmlhttp");
  11.     xmlhttp.open("post", urlstr, false);
  12.     xmlhttp.setrequestheader("content-type""application/x-www-form-urlencoded");
  13.     if (xmlstr) {
  14.         xmlhttp.send(xmlstr);
  15.     } else {
  16.         xmlhttp.send();
  17.     }
  18.     return xmlhttp.responsexml;
  19. }



    struts中我们扩展了action,实现了xmlstr转化成document对象(dom4j),并且完善了转发方式。如
[quote]
1.dispatchaction
     以一个controller响应一组动作绝对是controller界的真理,struts的dispatchaction同样可以做到这点。

[list]
<action path="/admin/user" name="userform" scope="request" parameter="method" validate="false">
    <forward name="list" path="/admin/userlist.jsp"/>
</action>
[/list]
    其中parameter="method" 设置了用来指定响应方法名的url参数名为method,即/admin/user.do?method=list 将调用useraction的public actionforward list(....) 函数。   

    public actionforward unspecified(....) 函数可以指定不带method方法时的默认方法。[/quote]
    但是这样需要在url后多传递参数[size=18][color=red]method=list [/color][/size];并且action节点配置中的[color=red]parameter="method" [/color]
也没有被充分利用,反而觉得是累赘!

    因此我们直接在basedispatchaction中增加xml字符串解析,并充分利用action节点配置中的[color=red]parameter="targetmethod" [/color],使得转发的时候,action能够直接转发到子类的相应方法中,减少了url参数传递,增强了配置信息可读性,方便团队开发。
    同样以上述为例,扩展后的配置方式如下:
[quote]
<action path="/admin/user" scope="request" [color=red]parameter="list"[/color] validate="false">
    <forward name="list" path="/admin/userlist.jsp"/>
</action>  
 [/quote]
    其中[color=red]parameter="list"[/color] 设置了用来指定响应url=/admin/user.do的方法名,它将调用useraction的public actionforward list(....) 函数。 
     basedispatchdocumentaction 的代码如下,它做了三件重要的事情:
     1、采用dom4j直接解析xml字符串,并返回document,如果没有提交xml数据,或者采用form形式提交的话,返回null;
     2、采用模版方法处理系统异常,减少了子类中无尽的try{...}catch(){...};其中异常处理部分另作描述(你可以暂时去掉异常处理,实现xml提交和解析,如果你有兴趣,我们可以进一步交流);


     3、提供了spring配置bean的直接调用,虽然她没有注入那么优雅,但是实现了ajax、struts、spring的结合。
basedispatchdocumentaction 的源码如下:

  1. package com.ufida.haisheng.struts;
  2. import java.io.ioexception;
  3. import java.io.printwriter;
  4. import java.lang.reflect.invocationtargetexception;
  5. import java.lang.reflect.method;
  6. import java.math.bigdecimal;
  7. import java.sql.timestamp;
  8. import java.util.date;
  9. import java.util.hashmap;
  10. import javax.servlet.http.httpservletrequest;
  11. import javax.servlet.http.httpservletresponse;
  12. import javax.servlet.http.httpsession;
  13. import org.apache.commons.beanutils.convertutils;
  14. import org.apache.commons.beanutils.converters.bigdecimalconverter;
  15. import org.apache.commons.beanutils.converters.classconverter;
  16. import org.apache.commons.beanutils.converters.integerconverter;
  17. import org.apache.commons.beanutils.converters.longconverter;
  18. import org.apache.log4j.logger;
  19. import org.apache.struts.action.action;
  20. import org.apache.struts.action.actionform;
  21. import org.apache.struts.action.actionforward;
  22. import org.apache.struts.action.actionmapping;
  23. import org.apache.struts.util.messageresources;
  24. import org.dom4j.document;
  25. import org.dom4j.io.saxreader;
  26. import org.hibernate.hibernateexception;
  27. import org.springframework.beans.beansexception;
  28. import org.springframework.context.applicationcontext;
  29. import org.springframework.dao.dataaccessexception;
  30. import org.springframework.web.context.support.webapplicationcontextutils;
  31. import com.ufida.haisheng.constants.globals;
  32. import com.ufida.haisheng.converter.dateconverter;
  33. import com.ufida.haisheng.converter.timestampconverter;
  34. import com.ufida.haisheng.exp.exceptiondto;
  35. import com.ufida.haisheng.exp.exceptiondisplaydto;
  36. import com.ufida.haisheng.exp.exceptionhandler.exceptionhandlerfactory;
  37. import com.ufida.haisheng.exp.exceptionhandler.exceptionutil;
  38. import com.ufida.haisheng.exp.exceptionhandler.iexceptionhandler;
  39. import com.ufida.haisheng.exp.exceptions.baseappexception;
  40. import com.ufida.haisheng.exp.exceptions.mappingconfigexception;
  41. import com.ufida.haisheng.exp.exceptions.nosuchbeanconfigexception;
  42. /**
  43.  * 系统的ajax转发基类。增加模版处理异常信息。
  44.  * 
  45.  * @author 陈志平 chenzp
  46.  * @desc basedispatchdocumentaction.java
  47.  * 
  48.  * @说明: web 应用基础平台
  49.  * @date 2005-03-02 11:18:01 am
  50.  * @版权所有: all right reserved 2006-2008
  51.  */
  52. public abstract class basedispatchdocumentaction extends action {
  53.     protected class clazz = this.getclass();
  54.     protected static logger log = logger.getlogger(basedispatchdocumentaction.class);
  55.     /**
  56.      * 异常信息
  57.      */
  58.     protected static threadlocal<exceptiondisplaydto> 
    expdisplaydetails = new threadlocal<exceptiondisplaydto>();
  59.     
  60.     private static final long defaultlong = null;
  61.     private static applicationcontext ctx = null;
  62.     /**
  63.      * 注册转换的工具类 使得from中的string --
  64.      * model中的对应的类型(date,bigdecimal,timestamp,double...)
  65.      */
  66.     static {
  67.         convertutils.register(new classconverter(), double.class);
  68.         convertutils.register(new dateconverter(), date.class);
  69.         convertutils.register(new dateconverter(), string.class);
  70.         convertutils.register(new longconverter(defaultlong), long.class);
  71.         convertutils.register(new integerconverter(defaultlong), integer.class);
  72.         convertutils.register(new timestampconverter(), timestamp.class);
  73.         convertutils.register(new bigdecimalconverter(defaultlong), bigdecimal.class);
  74.     }
  75.     /**
  76.      * the message resources for this package.
  77.      */
  78.     protected static messageresources messages = messageresources.getmessageresources("org.apache.struts.actions.localstrings");
  79.     /**
  80.      * the set of method objects we have introspected for this class, keyed by
  81.      * method name. this collection is populated as different methods are
  82.      * called, so that introspection needs to occur only once per method name.
  83.      */
  84.     protected hashmap<stringmethod> methods = new hashmap<stringmethod>();
  85.     /**
  86.      * the set of argument type classes for the reflected method call. these are
  87.      * the same for all calls, so calculate them only once.
  88.      */
  89.     protected class[] types = { actionmapping.class, actionform.classdocument.classhttpservletrequest.class,
  90.             httpservletresponse.class };
  91.     /**
  92.      * process the specified http request, and create the corresponding http
  93.      * response (or forward to another web component that will create it).
  94.      * return an <code>actionforward</code> instance describing where and how
  95.      * control should be forwarded, or <code>null</code> if the response has
  96.      * already been completed.
  97.      * 
  98.      * @param mapping
  99.      *            the actionmapping used to select this instance
  100.      * @param form
  101.      *            the optional actionform bean for this request (if any)
  102.      * @param request
  103.      *            the http request we are processing
  104.      * @param response
  105.      *            the http response we are creating
  106.      * 
  107.      * @exception exception
  108.      *                if an exception occurs
  109.      */
  110.     public actionforward execute(actionmapping mapping, actionform form, httpservletrequest request,
  111.             httpservletresponse response) throws exception {
  112.         response.setcontenttype("text/html; charset=utf-8");
  113.         exceptiondisplaydto expdto = null;
  114.         try {
  115.             document doc = createdocumentfromrequest(request);
  116.             /*
  117.              * 这里直接调用mapping的parameter配置
  118.              */
  119.             string actionmethod = mapping.getparameter();
  120.             /*
  121.              * 校验配置的方法是否正确、有效
  122.              */
  123.             isvalidmethod(actionmethod);
  124.             return dispatchmethod(mapping, form, doc, request, response, actionmethod);
  125.         } catch (baseappexception ex) {
  126.             expdto = handlerexception(request, response, ex);
  127.         } catch (exception ex) {
  128.             exceptionutil.logexception(this.getclass(), ex);
  129.             rendertext(response,"[error :对不起,系统出现错误了,请向管理员报告以下异常信息./n" + ex.getmessage() + "]");
  130.             request.setattribute(globals.errormsg, "对不起,系统出现错误了,请向管理员报告以下异常信息./n" + ex.getmessage());
  131.             expdto = handlerexception(request,response, ex);
  132.         } finally {
  133.             expdisplaydetails.set(null);
  134.         }
  135.         return null == expdto ? null : (expdto.getactionforwardname() == null ? null : mapping.findforward(expdto.getactionforwardname()));
  136.     }
  137.     /**
  138.      * 直接输出纯字符串
  139.      */
  140.     public void rendertext(httpservletresponse response, string text) {
  141.         printwriter out = null;
  142.         try {
  143.             out = response.getwriter();
  144.             response.setcontenttype("text/plain;charset=utf-8");
  145.             out.write(text);
  146.         } catch (ioexception e) {
  147.             log.error(e);
  148.         } finally {
  149.             if (out != null) {
  150.                 out.flush();
  151.                 out.close();
  152.                 out = null;
  153.             }
  154.         }
  155.     }
  156.     
  157.     /**
  158.      * 直接输出纯html
  159.      */
  160.     public void renderhtml(httpservletresponse response, string text) {
  161.         printwriter out = null;
  162.         try {
  163.             out = response.getwriter();
  164.             response.setcontenttype("text/html;charset=utf-8");
  165.             out.write(text);
  166.         } catch (ioexception e) {
  167.             log.error(e);
  168.         } finally {
  169.             if (out != null) {
  170.                 out.flush();
  171.                 out.close();
  172.                 out = null;
  173.             }
  174.         }
  175.     }
  176.     /**
  177.      * 直接输出纯xml
  178.      */
  179.     public void renderxml(httpservletresponse response, string text) {
  180.         printwriter out = null;
  181.         try {
  182.             out = response.getwriter();
  183.             response.setcontenttype("text/xml;charset=utf-8");
  184.             out.write(text);
  185.         } catch (ioexception e) {
  186.             log.error(e);
  187.         } finally {
  188.             if (out != null) {
  189.                 out.flush();
  190.                 out.close();
  191.                 out = null;
  192.             }
  193.         }
  194.     }
  195.     /**
  196.      * 异常处理
  197.      * @param request
  198.      * @param out
  199.      * @param ex
  200.      * @return exceptiondisplaydto异常描述对象
  201.      */
  202.     private exceptiondisplaydto handlerexception(httpservletrequest request,httpservletresponse response, exception ex) {
  203.         exceptiondisplaydto expdto = (exceptiondisplaydto) expdisplaydetails.get();
  204.         if (null == expdto) {            
  205.             expdto = new exceptiondisplaydto(null,this.getclass().getname());
  206.         }
  207.         iexceptionhandler exphandler = exceptionhandlerfactory.getinstance().create();
  208.         exceptiondto exdto = exphandler.handleexception(expdto.getcontext(), ex);
  209.         request.setattribute("exceptiondto", exdto);
  210.         rendertext(response,"[error:" + (exdto == null ? "exceptiondto is null,请检查expinfo.xml配置文件." : exdto.getmessagecode())
  211.                 + "]");
  212.         return expdto;
  213.     }
  214.     private void isvalidmethod(string actionmethod) throws mappingconfigexception {
  215.         if (actionmethod == null || "execute".equals(actionmethod) || "perform".equals(actionmethod)) {
  216.             log.error("[basedispatchaction->error] parameter = " + actionmethod);
  217.             expdisplaydetails.set(new exceptiondisplaydto(null"mappingconfigexception"));
  218.             throw new mappingconfigexception("对不起,配置的方法名不能为 " + actionmethod);
  219.         }
  220.     }
  221.   /**
  222.      * 解析xml流
  223.      * @param request
  224.      * @return document对象
  225.      */
  226.     protected static document createdocumentfromrequest(httpservletrequest request) throws exception {
  227.         try {
  228.             request.setcharacterencoding("utf-8");
  229.             document document = null;
  230.             saxreader reader = new saxreader();
  231.             document = reader.read(request.getinputstream());
  232.             return document;
  233.         } catch (exception ex) {
  234.             log.warn("tips:没有提交获取xml格式数据流! ");
  235.             return null;
  236.         }
  237.     }
  238.     /**
  239.      * dispatch to the specified method.
  240.      * 
  241.      * @since struts 1.1
  242.      */
  243.     protected actionforward dispatchmethod(actionmapping mapping, actionform form, document doc,httpservletrequest request, 
    httpservletresponse response, string name) throws exception {
  244.         method method = null;
  245.         try {
  246.             method = getmethod(name);
  247.         } catch (nosuchmethodexception e) {
  248.             string message = messages.getmessage("dispatch.method", mapping.getpath(), name);
  249.             log.error(message, e);
  250.             expdisplaydetails.set(new exceptiondisplaydto(null"mappingconfigexception"));
  251.             throw new mappingconfigexception(message, e);
  252.         }
  253.         actionforward forward = null;
  254.         try {
  255.             object args[] = { mapping, form, doc, request, response };
  256.             log.debug("[execute-begin] -> " + mapping.getpath() + "->[" + clazz.getname() + "->" + name + "]");
  257.             forward = (actionforward) method.invoke(this, args);
  258.             log.debug(" [execute-end] -> " + (null == forward ? "use ajax send to html/htm" : forward.getpath()));
  259.         } catch (classcastexception e) {
  260.             string message = messages.getmessage("dispatch.return", mapping.getpath(), name);
  261.             log.error(message, e);
  262.             throw new baseappexception(message, e);
  263.         } catch (illegalaccessexception e) {
  264.             string message = messages.getmessage("dispatch.error", mapping.getpath(), name);
  265.             log.error(message, e);
  266.             throw new baseappexception(message, e);
  267.         } catch (invocationtargetexception e) {
  268.             throwable t = e.gettargetexception();
  269.             string message = messages.getmessage("dispatch.error", mapping.getpath(), name);
  270.             throw new baseappexception(message, t);
  271.         }
  272.         return (forward);
  273.     }
  274.     /**
  275.      * introspect the current class to identify a method of the specified name
  276.      * that accepts the same parameter types as the <code>execute</code>
  277.      * method does.
  278.      * 
  279.      * @param name
  280.      *            name of the method to be introspected
  281.      * 
  282.      * @exception nosuchmethodexception
  283.      *                if no such method can be found
  284.      */
  285.     protected method getmethod(string name) throws nosuchmethodexception {
  286.         synchronized (methods) {
  287.             method method = (method) methods.get(name);
  288.             if (method == null) {
  289.                 method = clazz.getmethod(name, types);
  290.                 methods.put(name, method);
  291.             }
  292.             return (method);
  293.         }
  294.     }
  295.   /**
  296.    * 返回spring bean对象
  297.    * @param name spring bean的名称
  298.    * @exception baseappexception
  299.    */
  300.     protected object getspringbean(string name) throws baseappexception {
  301.         if (ctx == null) {
  302.             ctx = webapplicationcontextutils.getwebapplicationcontext(this.getservlet().getservletcontext());
  303.         }
  304.         object bean = null;
  305.         try {
  306.             bean = ctx.getbean(name);
  307.         } catch (beansexception ex) {
  308.             throw new nosuchbeanconfigexception("对不起,您没有配置名为:" + name + "的bean。请检查配置文件!", ex.getrootcause());
  309.         }
  310.         if (null == bean) {
  311.             throw new nosuchbeanconfigexception("对不起,您没有配置名为:" + name + "的bean。请检查配置文件!");
  312.         }
  313.         return bean;
  314.     }
  315. }


 


开发人员只需要继承它就可以了,我们写个简单的示例action,如下:

  1. /**
  2.  * 带ajax提交xml数据的action类模版
  3.  * 
  4.  * @author 陈志平 chenzp
  5.  * 
  6.  * @说明: web 应用基础平台
  7.  * @date aug 1, 2006 10:52:13 am
  8.  * @版权所有: all right reserved 2006-2008
  9.  */
  10. public class useraction extends basedispatchdocumentaction {
  11.          /**
  12.           * 这里 actionform 和 doc 参数必有一个为空,请聪明的你分析一下
  13.           * @param mapping --转发的映射对象
  14.           [color=blue]* @param actionform --仍然支持表单提交,此时doc == null
  15.           * @param doc document对象,解析xml后的文档对象[/color]
  16.           * @param request --请求
  17.           * @param response --响应
  18.           */
  19.     public actionforward list(actionmapping mapping, actionform actionform, [color=red]document doc[/color],httpservletrequest request, httpservletresponse response) throws baseappexception {
  20.         /**
  21.          * 转发的名称 useraction.search: 系统上下文 用于异常处理
  22.          */
  23.         expdisplaydetails.set(new exceptiondisplaydto(null"useraction.search"));
  24.         /**
  25.          * 处理业务逻辑部分:
  26.          * 
  27.          * 获取各种类型的参数 requestutil.getstrparameter(request,"parametername");
  28.          * 
  29.          * 调用父类的 getspringbean("serviceid")方法获取spring的配置bean
  30.          * 
  31.          */
  32.         usermanager usermanager = (logmanager) getspringbean("usermanager");
  33.         //返回xml对象到前台
  34.         renderxml(response, usermanager.findusersbydoc(doc));        
  35.                      return null;
  36.     }



至此,我们成功实现了ajax--struts--spring的无缝结合,下次介绍spring的开发应用。欢迎大家拍砖!

扫描关注微信公众号