xmlhttpservlet.java

来自「管理公司合同」· Java 代码 · 共 400 行

JAVA
400
字号
package cn.com.juneng.system.common.xmlhttp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import cn.com.juneng.system.common.SpringBeanFactory;

/**
 * XML HTTP SERVLET
 * 
 * @Copyright ©2005 hnisi , Inc.All rights reserved
 * @author yehailong
 * @version 1.0, 2005-09-03
 */
public class XmlHttpServlet extends HttpServlet {

	// Initialize global variables
	public void init() throws ServletException {
		SpringBeanFactory.setServletContext(this.getServletContext());
	}

	// Process the HTTP Get request
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String[] returnArr = null;
		Object returnObj = null;
		// request.setCharacterEncoding("GBK");
		try {
			String serviceName = request.getParameter("serviceName");
			String methodName = request.getParameter("methodName");
			String[] params = request.getParameterValues("param");
			if (serviceName.equalsIgnoreCase("request")
					|| serviceName.equalsIgnoreCase("session")) {
				returnObj = this.getRequestValue(serviceName, methodName,
						request);
			} else if (methodName.equals("setSession")) {
				returnObj = this.setSession(request, params);
			} else {
				Class serviceClass = null;
				try {
					serviceClass = Class.forName(serviceName);
				} catch (Exception e) {
					throw new Exception("class:'" + serviceName + "'未定义!");
				}
				Object service = serviceClass.newInstance();
				Method[] methods = serviceClass.getMethods();
				List paramTypeList = new ArrayList();
				for (int i = 0; i < methods.length; i++) {
					if (methods[i].getName().equals(methodName)) {
						// 可能涉及到多个同名函数
						paramTypeList.add(methods[i].getParameterTypes());
					}
				}
				if (paramTypeList.size() == 0) {
					throw new XmlHttpException("remote function:" + methodName
							+ " not found!");
				}
				Object[] params1 = convert(params, paramTypeList);
				// 解析返回值
				returnObj = MethodUtils.invokeMethod(service, methodName,
						params1);
			}
			returnObj = parseReturn(returnObj);
		} catch (XmlHttpException e) {
			e.printStackTrace();
			returnArr = new String[2];
			returnArr[0] = "0";
			returnArr[1] = e.getMessage();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			returnArr = new String[2];
			returnArr[0] = "0";
			returnArr[1] = e.getCause().getMessage();
		} catch (Exception e) {
			e.printStackTrace();
			returnArr = new String[2];
			returnArr[0] = "0";
			returnArr[1] = e.getMessage();
		}
		// 使用xml包装返回值
		if (returnObj == null) {
			processResponse(response, returnArr);
		} else {
			processResponse(response, returnObj);
		}

	}

	private void upload(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String fileName = request.getParameter("fileName");

		String realPath = this.getServletContext().getRealPath("/");
		String realFile = realPath + "wf" + File.separator + "WebFlow"
				+ File.separator + "flows" + File.separator + fileName;
		InputStream is = request.getInputStream();
		OutputStream os = new FileOutputStream(new File(realFile));

		byte[] b = new byte[2048];
		int len;
		while ((len = is.read(b)) > 0) {
			os.write(b, 0, len);
		}
		is.close();

		os.flush();
		os.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if ("upload".equals(request.getParameter("mode"))) {
			this.upload(request, response);
		}
	}

	public String setSession(HttpServletRequest request, String[] params)
			throws Exception {
		if (params == null || params.length != 2) {
			throw new Exception("使用错误,请指定存入SESSION的属性名和属性值!");
		}
		request.getSession().setAttribute(params[0], params[1]);
		return params[1];
	}

	/**
	 * 从session或request中获取信息
	 * 
	 * @param serviceName
	 * @param methodName
	 * @param request
	 * @return
	 */
	private Object getRequestValue(String serviceName, String methodName,
			HttpServletRequest request) {
		// Attribute Name
		String attrName = methodName;
		String propName = "";
		if (methodName.indexOf(".") != -1) {
			attrName = methodName.substring(0, attrName.indexOf("."));
			propName = methodName.substring(methodName.indexOf(".") + 1);
		}
		Object obj = null;
		if (serviceName.equalsIgnoreCase("request")) {
			obj = request.getAttribute(attrName);
		}
		if (serviceName.equalsIgnoreCase("session")) {
			obj = request.getSession().getAttribute(attrName);
		}
		if (propName.length() == 0) {
			return "" + obj;
		} else if (obj == null) {
			return "" + null;
		} else {

			try {
				return "" + PropertyUtils.getProperty(obj, propName);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "" + null;
	}

	private void processResponse(HttpServletResponse response, Object returnObj) {
		try {
			String returnXmlStr = buildXMLString(returnObj);
			// response.setCharacterEncoding("GBK");
			response.setContentType("text/xml");
			OutputStream out = response.getOutputStream();
			response.getOutputStream().write(returnXmlStr.getBytes("GBK"));
			out.close();
		} catch (Exception e) {
			// log.error("xml http 回传数据失败", t);
		}
	}

	private String buildXMLString(Object returnObj) {
		if (returnObj instanceof Document)
			return dom2String((Document) returnObj);
		return defaultXMLString((String[]) returnObj);

	}

	private String dom2String(Document doc) {

		StringWriter sw = new StringWriter();
		OutputFormat format = new OutputFormat();
		format.setEncoding("GBK");
		XMLWriter writer = new XMLWriter(sw, format);

		try {
			writer.write(doc);
			writer.flush();
		} catch (Exception e) {
			throw new RuntimeException("Document 转化为 String 失败", e);
		}
		return sw.toString();
	}

	private String defaultXMLString(String infor[]) {
		StringBuffer response = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"GBK\"?><response>");

		if (infor != null && infor.length > 0) {
			response.append("<size>");
			response.append(infor.length);
			response.append("</size>");
			for (int i = 0; i < infor.length; i++) {
				response.append("<infor id=\"");
				response.append(i);
				response.append("\"><![CDATA[");
				response.append(infor[i] != null ? infor[i] : "");
				response.append("]]></infor>");
			}
		} else {
			response.append("<size>0</size>");
		}

		response.append("</response>");
		return response.toString();
	}

	private String trans(String str) {
		String result = null;
		try {
			result = URLDecoder.decode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param returnObj
	 * @return Object
	 *         <LI>如果被调用函数返回Document,则返回值是Document
	 *         <LI>如果被调用函数返回一般对象(包括Array/Collection/Map),统一包装成数组返回
	 */
	private Object parseReturn(Object returnObj) {
		String[] returnArr = null;
		if (returnObj != null) {
			List returnList = new ArrayList();
			// System.out.println(returnObj.getClass().getName());
			if (returnObj instanceof Document) {
				return returnObj;
			} else if (returnObj.getClass().isArray()) {
				int len = Array.getLength(returnObj);
				returnArr = new String[len];
				for (int i = 0; i < len; i++) {
					returnArr[i] = Array.get(returnObj, i).toString();
				}
			} else if (returnObj instanceof Collection) {
				// 对象为集合
				Collection returns = (Collection) returnObj;
				Object[] temp = returns.toArray();
				returnArr = new String[temp.length];
				for (int i = 0; i < temp.length; i++) {
					returnArr[i] = temp[i].toString();
				}
			} else if (returnObj instanceof Map) {
				// 对象为Map
				Map map = (Map) returnObj;
				returnArr = new String[map.size()];
				Iterator it = map.keySet().iterator();
				int i = 0;
				Object key;
				while (it.hasNext()) {
					key = it.next();
					returnArr[i] = key.toString() + ":" + map.get(key);
					i++;
				}
			} else {
				returnArr = new String[1];
				returnArr[0] = returnObj.toString();
			}
		}
		String[] returnArr1 = new String[1 + (returnArr == null ? 0
				: returnArr.length)];
		returnArr1[0] = "1";// 表明是成功执行
		if (returnArr != null) {
			System.arraycopy(returnArr, 0, returnArr1, 1, returnArr.length);
		}
		return returnArr1;
	}

	private Object[] convert(String[] params, List paramTypeList)
			throws XmlHttpException {
		boolean noParam = false;
		StringBuffer paramCount = new StringBuffer();
		Class[] paramTypes = null;
		Map paramTypesMap = new HashMap();
		for (int i = 0; i < paramTypeList.size(); i++) {
			paramTypes = (Class[]) paramTypeList.get(i);
			if (paramTypes.length == 0) {
				noParam = true;
			}
			if (paramCount.length() != 0) {
				paramCount.append("或");
			}
			paramCount.append("" + paramTypes.length);
			paramTypesMap.put(new Integer(paramTypes.length), paramTypes);
		}
		if (params == null) {
			if (!noParam) {
				throw new XmlHttpException("错误的参数传递,应给被调用函数传递" + paramCount
						+ "个参数值!");
			} else {
				return null;
			}
		}
		paramTypes = (Class[]) paramTypesMap.get(new Integer(params.length));
		if (paramTypes == null) {
			throw new XmlHttpException("错误的参数传递,应给被调用函数传递" + paramCount
					+ "个参数值!");
		}
		Object[] obj = new Object[params.length];
		String param = "";
		Class paramType = null;
		for (int i = 0; i < params.length; i++) {
			param = trans(params[i]);
			paramType = paramTypes[i];
			Class[] temp = new Class[1];
			try {
				temp[0] = Class.forName("java.lang.String");
				if (!paramType.isPrimitive()) {
					Constructor constructor = paramType.getConstructor(temp);
					String[] initargs = { param };
					obj[i] = constructor.newInstance(initargs);
				} else {
					// 基本类型
					if (Integer.TYPE == paramType) {
						obj[i] = new Integer(param);
					} else if (Double.TYPE == paramType) {
						obj[i] = new Double(param);
					} else if (Boolean.TYPE == paramType) {
						obj[i] = new Boolean(param);
					} else if (Long.TYPE == paramType) {
						obj[i] = new Long(param);
					} else if (Float.TYPE == paramType) {
						obj[i] = new Float(param);
					} else if (Character.TYPE == paramType) {
						// TODO 如果是char类型参数,以下处理方式不正确
						// TODO 暂不支持char类型,抛出异常
						// obj[i] = new Character(param.charAt(0));
						throw new XmlHttpException("暂不支持参数类型为char的处理!");
					} else if (Byte.TYPE == paramType) {
						obj[i] = new Byte(param);
					} else if (Short.TYPE == paramType) {
						obj[i] = new Short(param);
					}
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				throw new XmlHttpException("传递的参数值“" + param + "”与参数类型“"
						+ paramType + "”不相符!");
			} catch (Exception e) {
				e.printStackTrace();
				String message = e.getMessage();
				if (message == null) {
					message = e.getCause().getMessage();
				}
				throw new XmlHttpException("方法调用失败:" + message);
			}
		}
		return obj;
	}

	// Clean up resources
	public void destroy() {
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?