All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.j2mvc.framework.dispatcher.reader.JSONReader Maven / Gradle / Ivy

Go to download

强烈建议使用J2mvc 2.1以后的版本。 version 2.1.01 1.优化路径跳转,Servlet和Filter方式的路径设置 2.优化内存销毁 3.更换JSON依赖包 4.优化接收方法RequestMethod,封装不同ContentType格式提交 封装JSON,XML数据提交模块 JSON请求示例 { "id":"JSON134851", "title":"JSON提交的标题", "price":65.1, "stock":100 } XML请求示例 <!DOCTYPE root [ <!ELEMENT root ANY> <!ATTLIST Product SSN ID #REQUIRED>]> <root> <Product SSN='id'>XMLID12354</Product> <Product SSN='title'>XML提交的标题 </Product> <Product SSN='price'>55 </Product> <Product SSN='stock'>32 </Product> </root> version 2.1.02 1.解决URL无后缀情况无法加载静态资源,解决无法渲染CSS文件。 version 2.1.03 1.移除com.j2mvc.StringUtils.getUtf8()方法调用 更改为getCharset() version 2.1.04 1.去除Servlet和Filter的全局变量销毁,只交给Listener处理。 version 2.1.05,2.1.06,2.1.07 1.完善POST提交的JSON数据 支持接收基础数据类型、任意对象类型、任意数组类型。 不支持接收参数为集合类型或Map类型,但可以定义为接收对象类型的元素。 version 2.1.05,2.1.06,2.1.07 1.修改连接池变量 version 2.1.09 增加上传功能,修改RequestMethod,ContentType设置方式 version 2.1.10,2.1.11 更改上传文件名格式为UUID格式,移除JSON映射类,更改接收多文件上传。 version 2.1.12 删除文件列有的空对象 version 2.1.13 增加配置文件目录/conf,加载上传功能配置/conf/upload.properties version 2.1.18 拦截器也能获取ActionBean version 2.1.20 添加上传文件只读权限 version 2.1.21 支持同时接收文件和文本数据 version 2.1.22 增加文件接收类型media version 2.1.23 删除upload类printJson方法

There is a newer version: 2.1.39
Show newest version
package com.j2mvc.framework.dispatcher.reader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Time;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.j2mvc.framework.Constants;
import com.j2mvc.framework.Session;
import com.j2mvc.framework.action.RequestUri;
import com.j2mvc.framework.util.InvokeUtils;
import com.j2mvc.util.StringUtils;
import com.j2mvc.util.json.JSONParse;

/**
 * 读JSON数据并解析
 * 
 * @author 杨朔 2019-6-7
 */
public class JSONReader extends BaseReader {
	static final Logger log = Logger.getLogger(JSONReader.class);

	public JSONReader(HttpServletRequest request, Method method, Object object) {
		super(request, method, object);
	}

	/**
	 * 读取请求参数的数据 需要区分请求方法和数据提交类型 读取JSON数据,并解析出对象返回
	 * 
	 * @param method
	 * @param object
	 * @return Object
	 */
	public Object result() {
		clazz = object.getClass();
		types = method.getParameterTypes();
		int length = types.length;
		if (length > 0) {
			// 请求参数名数组
			names = getParameterNames(clazz, method.getName(), length);
			values = new Object[types.length];
			if (names != null) {
				// 将json字符串转换为json对象
				try {
					requestBody();
					jsonData = JSONObject.parseObject(requestBody);
					// 解析JSON数据
					for (int i = 0; i < types.length; i++) {
						Class type = types[i];
						values[i] = getParameterValue(type, names[i]);
					}
					InvokeUtils.invoke(clazz, "setJsonData", object, new Object[] { jsonData }, JSONObject.class);
					InvokeUtils.invoke(clazz, "setRequestBody", object, new Object[] { requestBody }, String.class);
					try {
						log.info(method.getName()+values);
						return method.invoke(object, values);
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (JSONException e) {
					log.error("JSON格式解析错误!");
					e.printStackTrace();
				}
			}
		} else {
			// 没有参数,执行当前Action方法
			return InvokeUtils.invoke(clazz, method.getName(), object, null);
		}
		return null;
	}

	/**
	 * 读取数据流字符串
	 */
	public void requestBody() {
		try {
			request.setCharacterEncoding(Session.encoding);
		} catch (UnsupportedEncodingException e1) {
			log.error("字符编码错误!");
		}
		// 读取请求内容
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(request.getInputStream(), Session.encoding));
		} catch (UnsupportedEncodingException e1) {
			log.error("读取字符编码错误!");
		} catch (IOException e1) {
			log.error("读取数据失败!");
		}
		String line = null;
		StringBuilder sb = new StringBuilder();
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			requestBody = sb.toString();
		} catch (IOException e1) {
			log.error("读取数据失败!");
		}
	}

	/**
	 * 获取参数值
	 * 
	 * @param type
	 * @param name
	 * 
	 */
	@Override
	protected Object getParameterValue(Class type, String name) {
		if (RequestUri.class.isAssignableFrom(type)) {
			String path = request.getContextPath();
			String requestUri = request.getRequestURI();
			requestUri = StringUtils.deleRepeat(requestUri, "/");
			requestUri = requestUri.substring(path.length(), requestUri.length());
			requestUri = requestUri.startsWith("/") ? requestUri.substring(1, requestUri.length()) : requestUri;
			requestUri = requestUri.endsWith("/") ? requestUri.substring(0, requestUri.length() - 1) : requestUri;
			String[] values = requestUri.split("/");
			return new RequestUri(values);
		} else if (String.class.isAssignableFrom(type)) {
			return jsonData.getString(name);
		} else if (Integer.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type)
				|| short.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
			return jsonData.getInteger(name);
		} else if (Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type)) {
			return jsonData.getLong(name);
		} else if (Float.class.isAssignableFrom(type) || float.class.isAssignableFrom(type)) {
			return jsonData.getFloat(name);
		} else if (Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
			return jsonData.getDouble(name);
		} else if (Boolean.class.isAssignableFrom(type) || boolean.class.isAssignableFrom(type)) {
			return jsonData.getBoolean(name);
		} else if (Time.class.isAssignableFrom(type))
			try {
				String str = jsonData.getString(name);
				return Constants.DEFAULT_TIME_FORMAT.parse(str);
			} catch (ParseException e) {
				log.error(e.getMessage());
				return null;
			}
		else if (Date.class.isAssignableFrom(type)) {
			try {
				String str = jsonData.getString(name);
				return Constants.DEFAULT_DATE_TIME_FORMAT.parse(str);
			} catch (ParseException e) {
				log.error(e.getMessage());
				return null;
			}
		} else {
			String value = jsonData.getString(name);
			if(value == null) {
				return null;
			}
			if (type.isArray()) {
				Class clazz;
				try {
					clazz = Class.forName(type.getCanonicalName().replace("[]", ""));
					return JSONParse.parseArray(value, clazz);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
					return null;
				}
			} else if (Map.class.isAssignableFrom(type) || HashMap.class.isAssignableFrom(type)) {
				log.error("无法解析Map类型,请使用对象模式接收:"+name);
				return null;
			} else if (Set.class.isAssignableFrom(type) || 
					HashSet.class.isAssignableFrom(type) || 
					List.class.isAssignableFrom(type) || 
					ArrayList.class.isAssignableFrom(type)) {
				log.error("不支集合类型,请使用数组类型接收:"+name);
				return null;
			} else {
				// 尝试对象模式接收
				return JSONParse.parseObject(value, type);
			}
		}

	}

	@Override
	protected Object getValue(Class type, String name) {
		return null;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy