ITeye博客

转贴:主题:ajax、Struts、spring的无缝结合

abei1 · 2006-12-17 09:27 · Struts · Markdown

作者:zhipingch      出处:http://zhipingch.iteye.com/

去年初,正好负责一个医药信息系统的设计开发,架构设计时,采用Struts+JDBC(自定义采用适配器模式封装了HashMap动态VO实现的持久 层)。后来ajax热潮兴起,正好系统中有很多地方需要和服务器端交互数据,如采购销售系统中的订单头/订单明细等主从表结构的维护。
数据交互过程,我们考虑采用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. }

<script type="text/javascript">render_code();</script>

struts中我们扩展了Action,实现了xmlStr转化成document对象(dom4j),并且完善了转发方式。如

引用

1.DispatchAction
以一个Controller响应一组动作绝对是Controller界的真理,Struts的DispatchAction同样可以做到这点。

  • <action path="/admin/user" name="userForm" scope="request" parameter="method" validate="false">
    <forward name="list" path="/admin/userList.jsp"/>
    </action>

其中parameter="method" 设置了用来指定响应方法名的url参数名为method,即/admin/user.do?method=list 将调用UserAction的public ActionForward list(....) 函数。

public ActionForward unspecified(....) 函数可以指定不带method方法时的默认方法。

但是这样需要在url后多传递参数method=list ;并且action节点配置中的parameter="method"
也没有被充分利用,反而觉得是累赘!

因此我们直接在BaseDispatchAction中增加xml字符串解析,并充分利用action节点配置中的parameter="targetMethod" ,使得转发的时候,action能够直接转发到子类的相应方法中,减少了url参数传递,增强了配置信息可读性,方便团队开发。
同样以上述为例,扩展后的配置方式如下:

引用

<action path="/admin/user" scope="request" parameter="list" validate="false">
<forward name="list" path="/admin/userList.jsp"/>
</action>

其中parameter="list" 设置了用来指定响应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. private static final Long defaultLong = null;
  60. private static ApplicationContext ctx = null;
  61. /**
  62. * 注册转换的工具类 使得From中的string --
  63. * Model中的对应的类型(Date,BigDecimal,Timestamp,Double...)
  64. */
  65. static {
  66. ConvertUtils.register(new ClassConverter(), Double.class);
  67. ConvertUtils.register(new DateConverter(), Date.class);
  68. ConvertUtils.register(new DateConverter(), String.class);
  69. ConvertUtils.register(new LongConverter(defaultLong), Long.class);
  70. ConvertUtils.register(new IntegerConverter(defaultLong), Integer.class);
  71. ConvertUtils.register(new TimestampConverter(), Timestamp.class);
  72. ConvertUtils.register(new BigDecimalConverter(defaultLong), BigDecimal.class);
  73. }
  74. /**
  75. * The message resources for this package.
  76. */
  77. protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.actions.LocalStrings");
  78. /**
  79. * The set of Method objects we have introspected for this class, keyed by
  80. * method name. This collection is populated as different methods are
  81. * called, so that introspection needs to occur only once per method name.
  82. */
  83. protected HashMap<String, Method> methods = new HashMap<String, Method>();
  84. /**
  85. * The set of argument type classes for the reflected method call. These are
  86. * the same for all calls, so calculate them only once.
  87. */
  88. protected Class[] types = { ActionMapping.class, ActionForm.class, Document.class, HttpServletRequest.class,
  89. HttpServletResponse.class };
  90. /**
  91. * Process the specified HTTP request, and create the corresponding HTTP
  92. * response (or forward to another web component that will create it).
  93. * Return an <code>ActionForward</code> instance describing where and how
  94. * control should be forwarded, or <code>null</code> if the response has
  95. * already been completed.
  96. *
  97. * @param mapping
  98. *            The ActionMapping used to select this instance
  99. * @param form
  100. *            The optional ActionForm bean for this request (if any)
  101. * @param request
  102. *            The HTTP request we are processing
  103. * @param response
  104. *            The HTTP response we are creating
  105. *
  106. * @exception Exception
  107. *                if an exception occurs
  108. */
  109. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
  110. HttpServletResponse response) throws Exception {
  111. response.setContentType("text/html; charset=UTF-8");
  112. ExceptionDisplayDTO expDTO = null;
  113. try {
  114. Document doc = createDocumentFromRequest(request);
  115. /*
  116. * 这里直接调用mapping的parameter配置
  117. */
  118. String actionMethod = mapping.getParameter();
  119. /*
  120. * 校验配置的方法是否正确、有效
  121. */
  122. isValidMethod(actionMethod);
  123. return dispatchMethod(mapping, form, doc, request, response, actionMethod);
  124. } catch (BaseAppException ex) {
  125. expDTO = handlerException(request, response, ex);
  126. } catch (Exception ex) {
  127. ExceptionUtil.logException(this.getClass(), ex);
  128. renderText(response,"[Error :对不起,系统出现错误了,请向管理员报告以下异常信息.\n" + ex.getMessage() + "]");
  129. request.setAttribute(Globals.ERRORMSG, "对不起,系统出现错误了,请向管理员报告以下异常信息.\n" + ex.getMessage());
  130. expDTO = handlerException(request,response, ex);
  131. } finally {
  132. expDisplayDetails.set(null);
  133. }
  134. return null == expDTO ? null : (expDTO.getActionForwardName() == null ? null : mapping.findForward(expDTO.getActionForwardName()));
  135. }
  136. /**
  137. * 直接输出纯字符串
  138. */
  139. public void renderText(HttpServletResponse response, String text) {
  140. PrintWriter out = null;
  141. try {
  142. out = response.getWriter();
  143. response.setContentType("text/plain;charset=UTF-8");
  144. out.write(text);
  145. } catch (IOException e) {
  146. log.error(e);
  147. } finally {
  148. if (out != null) {
  149. out.flush();
  150. out.close();
  151. out = null;
  152. }
  153. }
  154. }
  155. /**
  156. * 直接输出纯HTML
  157. */
  158. public void renderHtml(HttpServletResponse response, String text) {
  159. PrintWriter out = null;
  160. try {
  161. out = response.getWriter();
  162. response.setContentType("text/html;charset=UTF-8");
  163. out.write(text);
  164. } catch (IOException e) {
  165. log.error(e);
  166. } finally {
  167. if (out != null) {
  168. out.flush();
  169. out.close();
  170. out = null;
  171. }
  172. }
  173. }
  174. /**
  175. * 直接输出纯XML
  176. */
  177. public void renderXML(HttpServletResponse response, String text) {
  178. PrintWriter out = null;
  179. try {
  180. out = response.getWriter();
  181. response.setContentType("text/xml;charset=UTF-8");
  182. out.write(text);
  183. } catch (IOException e) {
  184. log.error(e);
  185. } finally {
  186. if (out != null) {
  187. out.flush();
  188. out.close();
  189. out = null;
  190. }
  191. }
  192. }
  193. /**
  194. * 异常处理
  195. * @param request
  196. * @param out
  197. * @param ex
  198. * @return ExceptionDisplayDTO异常描述对象
  199. */
  200. private ExceptionDisplayDTO handlerException(HttpServletRequest request,HttpServletResponse response, Exception ex) {
  201. ExceptionDisplayDTO expDTO = (ExceptionDisplayDTO) expDisplayDetails.get();
  202. if (null == expDTO) {
  203. expDTO = new ExceptionDisplayDTO(null,this.getClass().getName());
  204. }
  205. IExceptionHandler expHandler = ExceptionHandlerFactory.getInstance().create();
  206. ExceptionDTO exDto = expHandler.handleException(expDTO.getContext(), ex);
  207. request.setAttribute("ExceptionDTO", exDto);
  208. renderText(response,"[Error:" + (exDto == null ? "ExceptionDTO is null,请检查expinfo.xml配置文件." : exDto.getMessageCode())
  209. + "]");
  210. return expDTO;
  211. }
  212. private void isValidMethod(String actionMethod) throws MappingConfigException {
  213. if (actionMethod == null || "execute".equals(actionMethod) || "perform".equals(actionMethod)) {
  214. log.error("[BaseDispatchAction->error] parameter = " + actionMethod);
  215. expDisplayDetails.set(new ExceptionDisplayDTO(null, "MappingConfigException"));
  216. throw new MappingConfigException("对不起,配置的方法名不能为 " + actionMethod);
  217. }
  218. }
  219. /**
  220. * 解析xml流
  221. * @param request
  222. * @return Document对象
  223. */
  224. protected static Document createDocumentFromRequest(HttpServletRequest request) throws Exception {
  225. try {
  226. request.setCharacterEncoding("UTF-8");
  227. Document document = null;
  228. SAXReader reader = new SAXReader();
  229. document = reader.read(request.getInputStream());
  230. return document;
  231. } catch (Exception ex) {
  232. log.warn("TIPS:没有提交获取XML格式数据流! ");
  233. return null;
  234. }
  235. }
  236. /**
  237. * Dispatch to the specified method.
  238. *
  239. * @since Struts 1.1
  240. */
  241. protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, Document doc,HttpServletRequest request, HttpServletResponse response, String name) throws Exception {
  242. Method method = null;
  243. try {
  244. method = getMethod(name);
  245. } catch (NoSuchMethodException e) {
  246. String message = messages.getMessage("dispatch.method", mapping.getPath(), name);
  247. log.error(message, e);
  248. expDisplayDetails.set(new ExceptionDisplayDTO(null, "MappingConfigException"));
  249. throw new MappingConfigException(message, e);
  250. }
  251. ActionForward forward = null;
  252. try {
  253. Object args[] = { mapping, form, doc, request, response };
  254. log.debug("[execute-begin] -> " + mapping.getPath() + "->[" + clazz.getName() + "->" + name + "]");
  255. forward = (ActionForward) method.invoke(this, args);
  256. log.debug(" [execute-end] -> " + (null == forward ? "use ajax send to html/htm" : forward.getPath()));
  257. } catch (ClassCastException e) {
  258. String message = messages.getMessage("dispatch.return", mapping.getPath(), name);
  259. log.error(message, e);
  260. throw new BaseAppException(message, e);
  261. } catch (IllegalAccessException e) {
  262. String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
  263. log.error(message, e);
  264. throw new BaseAppException(message, e);
  265. } catch (InvocationTargetException e) {
  266. Throwable t = e.getTargetException();
  267. String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
  268. throw new BaseAppException(message, t);
  269. }
  270. return (forward);
  271. }
  272. /**
  273. * Introspect the current class to identify a method of the specified name
  274. * that accepts the same parameter types as the <code>execute</code>
  275. * method does.
  276. *
  277. * @param name
  278. *            Name of the method to be introspected
  279. *
  280. * @exception NoSuchMethodException
  281. *                if no such method can be found
  282. */
  283. protected Method getMethod(String name) throws NoSuchMethodException {
  284. synchronized (methods) {
  285. Method method = (Method) methods.get(name);
  286. if (method == null) {
  287. method = clazz.getMethod(name, types);
  288. methods.put(name, method);
  289. }
  290. return (method);
  291. }
  292. }
  293. /**
  294. * 返回spring bean对象
  295. * @param name Spring Bean的名称
  296. * @exception BaseAppException
  297. */
  298. protected Object getSpringBean(String name) throws BaseAppException {
  299. if (ctx == null) {
  300. ctx = WebApplicationContextUtils.getWebApplicationContext(this.getServlet().getServletContext());
  301. }
  302. Object bean = null;
  303. try {
  304. bean = ctx.getBean(name);
  305. } catch (BeansException ex) {
  306. throw new NoSuchBeanConfigException("对不起,您没有配置名为:" + name + "的bean。请检查配置文件!", ex.getRootCause());
  307. }
  308. if (null == bean) {
  309. throw new NoSuchBeanConfigException("对不起,您没有配置名为:" + name + "的bean。请检查配置文件!");
  310. }
  311. return bean;
  312. }
  313. }

<script type="text/javascript">render_code();</script>
开发人员只需要继承它就可以了,我们写个简单的示例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. <span style="color:blue;">* @param actionForm --仍然支持表单提交,此时doc == null
  15. * @param doc document对象,解析xml后的文档对象</span>
  16. * @param request --请求
  17. * @param response --响应
  18. */
  19. public ActionForward list(ActionMapping mapping, ActionForm actionForm, <span style="color:red;">Document doc</span>,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));       return null;
  35. }

<script type="text/javascript">render_code();</script>

至此,我们成功实现了ajax--struts--spring的无缝结合。欢迎大家拍砖!

评论(1)

  1. #1 楼 · elvishehai · 2008-11-19 22:59

    有没有一包啊, 顾··

评论功能维护中,当前仅展示历史评论。