日期:2014-05-16 浏览次数:20545 次
?
一、目的:
JS客户端在编写程序时,可以像调用本地方法一样调用服务器端的Spring中Bean的方法,实现对Spring的动态调用,从而减少客户端的每个请求都要配置成action的麻烦,使业务模块的开发只关注业务逻辑的展示页面的开发。
二、设计思路:
1.服务器端利用Struts机制,提供统一的动态action,名称为DynamicAjaxAction,接收客户端的请求,并返回处理结果;
2.DynamicAjaxAction内部解析请求后,通过java反射机制动态调用spring中的baen方法;
3.客户端封装异步请求方法,提供调用接口;
总体架构如下示意图:
?
?
?
三、详细设计:
1.DynamicAjaxAction的设计:
public class DynamicAjaxAction extends ActionSupport { private ActionInvoker actionInvoker; private DynamicAjaxActionRouting routing; private static final Log log = LogFactory.getLog(DynamicAjaxAction.class); protected static ArrayList<String> ExcludeValues = new ArrayList<String>(); public DynamicAjaxAction() { ExcludeValues.add("_de"); ExcludeValues.add("serviceUrl"); ExcludeValues.add("cacheData"); } public String execute() throws Exception { log.debug("DynamicAjaxAction.execute"); String key = this.getServiceUrl(); Map<String, Object> session = ServletActionContext.getContext().getSession(); HttpServletResponse response = ServletActionContext.getResponse(); data = this.invokerAction(); if(data == null) ExtObject.writeJsonString(response, (new ExtResultObject(true)).toString()); else ExtObject.writeJsonString(response, data.toString()); return null; } protected Object invokerAction() throws Exception { Object[] params = this.getInvokerParams().toArray(); Object obj = actionInvoker.invokerAction(this.getRouting().getServiceName(), this.getRouting().getActionName(), params); return obj; } private String getServiceUrl() { HttpServletRequest request = ServletActionContext.getRequest(); String serviceUrl = request.getParameter("serviceUrl"); return serviceUrl; } private boolean isCacheData() { HttpServletRequest request = ServletActionContext.getRequest(); String serviceUrl = request.getParameter("cacheData"); if(StringUtility.isNullOrEmpty(serviceUrl)) return false; return serviceUrl.equals("true"); } protected DynamicAjaxActionRouting getRouting() { String serviceUrl = this.getServiceUrl(); routing = new DynamicAjaxActionRouting(serviceUrl); return routing; } @SuppressWarnings("unchecked") protected HashMap<String, Object> getRequestParams() { HttpServletRequest request = ServletActionContext.getRequest(); HashMap<String, Object> requestParams = new HashMap<String, Object>(); Object[] params = request.getParameterMap().keySet().toArray(); for(int i = params.length; i > 0; i --) { String item = params[i - 1].toString(); if(!ExcludeValues.contains(item)) { String[] value = request.getParameterValues(item); if(value.length == 0) { //do nothing } else if(value.length == 1) { requestParams.put(item, value[0]); } else { requestParams.put(item, value); } } } return requestParams; } @SuppressWarnings("unchecked") protected ArrayList getInvokerParams() { HttpServletRequest request = ServletActionContext.getRequest(); ArrayList requestParams = new ArrayList(); requestParams.addAll(this.getRouting().g