---
title: "转贴：主题:ajax、Struts、spring的无缝结合"
author: "abei1"
date: "2006-12-17T09:27:01Z"
tags: []
slug: "ajax-struts-spring"
draft: false
lastmod: "2006-12-17T09:27:01Z"
id: 39388
url: "https://abei1.iteye.com/blog/39388"
---

作者：**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）。

代码

01. /\**
02. * 将数据同步传递给后台请求url
03. *  @return 返回xmlhttp 响应的信息
04. *  @param-url = '/web/module/xxx.do?p1=YY&p2=RR';
05. *  @param-xmlStr：xml格式的字符串 &lt;data&gt;&lt;xpath&gt;&lt;!\[CDATA\[数据信息]]&gt;&lt;/xpath&gt;&lt;/data&gt;
06. * @author zhipingch
07. * @date 2005-03-17
08. \*/
09. 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. }

&lt;script type="text/javascript"&gt;render\_code();&lt;/script&gt;

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

引用

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

- &lt;action path="/admin/user" name="userForm" scope="request" parameter="method" validate="false"&gt;  
  &lt;forward name="list" path="/admin/userList.jsp"/&gt;  
  &lt;/action&gt;

其中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参数传递，增强了配置信息可读性，方便团队开发。  
同样以上述为例，扩展后的配置方式如下：

引用

&lt;action path="/admin/user" scope="request" parameter="list" validate="false"&gt;  
&lt;forward name="list" path="/admin/userList.jsp"/&gt;  
&lt;/action&gt;

其中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 的源码如下：

代码

001. package com.ufida.haisheng.struts;
002. import java.io.IOException;
003. import java.io.PrintWriter;
004. import java.lang.reflect.InvocationTargetException;
005. import java.lang.reflect.Method;
006. import java.math.BigDecimal;
007. import java.sql.Timestamp;
008. import java.util.Date;
009. import java.util.HashMap;
010. import javax.servlet.http.HttpServletRequest;
011. import javax.servlet.http.HttpServletResponse;
012. import javax.servlet.http.HttpSession;
013. import org.apache.commons.beanutils.ConvertUtils;
014. import org.apache.commons.beanutils.converters.BigDecimalConverter;
015. import org.apache.commons.beanutils.converters.ClassConverter;
016. import org.apache.commons.beanutils.converters.IntegerConverter;
017. import org.apache.commons.beanutils.converters.LongConverter;
018. import org.apache.log4j.Logger;
019. import org.apache.struts.action.Action;
020. import org.apache.struts.action.ActionForm;
021. import org.apache.struts.action.ActionForward;
022. import org.apache.struts.action.ActionMapping;
023. import org.apache.struts.util.MessageResources;
024. import org.dom4j.Document;
025. import org.dom4j.io.SAXReader;
026. import org.hibernate.HibernateException;
027. import org.springframework.beans.BeansException;
028. import org.springframework.context.ApplicationContext;
029. import org.springframework.dao.DataAccessException;
030. import org.springframework.web.context.support.WebApplicationContextUtils;
031. import com.ufida.haisheng.constants.Globals;
032. import com.ufida.haisheng.converter.DateConverter;
033. import com.ufida.haisheng.converter.TimestampConverter;
034. import com.ufida.haisheng.exp.ExceptionDTO;
035. import com.ufida.haisheng.exp.ExceptionDisplayDTO;
036. import com.ufida.haisheng.exp.exceptionhandler.ExceptionHandlerFactory;
037. import com.ufida.haisheng.exp.exceptionhandler.ExceptionUtil;
038. import com.ufida.haisheng.exp.exceptionhandler.IExceptionHandler;
039. import com.ufida.haisheng.exp.exceptions.BaseAppException;
040. import com.ufida.haisheng.exp.exceptions.MappingConfigException;
041. import com.ufida.haisheng.exp.exceptions.NoSuchBeanConfigException;
042. /\**
043. * 系统的Ajax转发基类。增加模版处理异常信息。
044. \*
045. * @author 陈志平 chenzp
046. * @desc BaseDispatchDocumentAction.java
047. \*
048. * @说明: web 应用基础平台
049. * @date 2005-03-02 11:18:01 AM
050. * @版权所有: All Right Reserved 2006-2008
051. \*/
052. public abstract class BaseDispatchDocumentAction extends Action {
053. protected Class clazz = this.getClass();
054. protected static Logger log = Logger.getLogger(BaseDispatchDocumentAction.class);
055. /\**
056. * 异常信息
057. \*/
058. protected static ThreadLocal&lt;ExceptionDisplayDTO&gt; expDisplayDetails = new ThreadLocal&lt;ExceptionDisplayDTO&gt;();
059. private static final Long defaultLong = null;
060. private static ApplicationContext ctx = null;
061. /\**
062. * 注册转换的工具类 使得From中的string --
063. * Model中的对应的类型(Date,BigDecimal,Timestamp,Double...)
064. \*/
065. static {
066. ConvertUtils.register(new ClassConverter(), Double.class);
067. ConvertUtils.register(new DateConverter(), Date.class);
068. ConvertUtils.register(new DateConverter(), String.class);
069. ConvertUtils.register(new LongConverter(defaultLong), Long.class);
070. ConvertUtils.register(new IntegerConverter(defaultLong), Integer.class);
071. ConvertUtils.register(new TimestampConverter(), Timestamp.class);
072. ConvertUtils.register(new BigDecimalConverter(defaultLong), BigDecimal.class);
073. }
074. /\**
075. * The message resources for this package.
076. \*/
077. protected static MessageResources messages = MessageResources.getMessageResources("org.apache.struts.actions.LocalStrings");
078. /\**
079. * The set of Method objects we have introspected for this class, keyed by
080. * method name. This collection is populated as different methods are
081. * called, so that introspection needs to occur only once per method name.
082. \*/
083. protected HashMap&lt;String, Method&gt; methods = new HashMap&lt;String, Method&gt;();
084. /\**
085. * The set of argument type classes for the reflected method call. These are
086. * the same for all calls, so calculate them only once.
087. \*/
088. protected Class\[] types = { ActionMapping.class, ActionForm.class, Document.class, HttpServletRequest.class,
089. HttpServletResponse.class };
090. /\**
091. * Process the specified HTTP request, and create the corresponding HTTP
092. * response (or forward to another web component that will create it).
093. * Return an &lt;code&gt;ActionForward&lt;/code&gt; instance describing where and how
094. * control should be forwarded, or &lt;code&gt;null&lt;/code&gt; if the response has
095. * already been completed.
096. \*
097. * @param mapping
098. *            The ActionMapping used to select this instance
099. * @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-&gt;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] -&gt; " + mapping.getPath() + "-&gt;\[" + clazz.getName() + "-&gt;" + name + "]");
255. forward = (ActionForward) method.invoke(this, args);
256. log.debug(" \[execute-end] -&gt; " + (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 &lt;code&gt;execute&lt;/code&gt;
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. }

&lt;script type="text/javascript"&gt;render\_code();&lt;/script&gt;  
开发人员只需要继承它就可以了，我们写个简单的示例action，如下：

代码

01. /\**
02. * 带Ajax提交xml数据的action类模版
03. \*
04. * @author 陈志平 chenzp
05. \*
06. * @说明: web 应用基础平台
07. * @date Aug 1, 2006 10:52:13 AM
08. * @版权所有: All Right Reserved 2006-2008
09. \*/
10. public class UserAction extends BaseDispatchDocumentAction {
11. /\**
12. * 这里 actionForm 和 doc 参数必有一个为空，请聪明的你分析一下
13. * @param mapping --转发的映射对象
14. &lt;span style="color:blue;"&gt;* @param actionForm --仍然支持表单提交，此时doc == null
15. * @param doc document对象，解析xml后的文档对象&lt;/span&gt;
16. * @param request --请求
17. * @param response --响应
18. \*/
19. public ActionForward list(ActionMapping mapping, ActionForm actionForm, &lt;span style="color:red;"&gt;Document doc&lt;/span&gt;,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. }

&lt;script type="text/javascript"&gt;render\_code();&lt;/script&gt;

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