java通过request自动封装复杂对象

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

参考:Jfinal源码,在上面基础上改的,然后分享出来
适用JAVAEE平台

 

[Java]代码    

/**
	 * 实现深层封装对象的实例 从request封装对象
	 * 举例:
	 * House.class 属性有三个 ID:id 名称:name 门类:Door door
	   Door类: id name height
	     传递的参数:house.id=5 & house.name=普通住宅 & door.id=33 & door.name=木门 & door.height=500 就可以自动封装
	 */
	private static final <T> T injectCommonModel(Object model, String modelName, HttpServletRequest request, Class<?> modelClass, boolean skipConvertError) throws Exception{
		Method[] methods = modelClass.getMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			if (methodName.startsWith("set") == false)	// only setter method
				continue;
			
			Class<?>[] types = method.getParameterTypes();
			if (types.length != 1)						// only one parameter
				continue;
			
			if(TypeConverter.judgeBasicType(types[0])){ //判断是否基本类型
				String attrName = methodName.substring(3);
				String value = request.getParameter(modelName + "." + StrKit.firstCharToLowerCase(attrName));
				if (value != null) {
					method.invoke(model, TypeConverter.convert(types[0], value));
				}
			}else{
				Object newModel = types[0].newInstance();
				String newModelName = newModel.getClass().getSimpleName();
				newModel = injectCommonModel(newModel, StrKit.firstCharToLowerCase(newModelName), request, newModel.getClass(), skipConvertError);
				if (newModel != null) {
					method.invoke(model, newModel);
				}
			}
		}
		return (T)model;
	}