HTTP请求bean转换工具

Java泛型详解 :[url]http://blog.csdn.net/jinuxwu/article/details/6771121[/url]
[url]http://www.cnblogs.com/tech-bird/p/3516325.html[/url]
[url]http://lichaozhangobj.iteye.com/blog/476911[/url]
的区别 :[url]http://blog.csdn.net/cgf1993/article/details/50754584[/url]
instanceof 与isAssignableFrom :[url]http://blog.csdn.net/kjfcpua/article/details/7045207[/url]
Java String和Date的转换:[url]http://www.cnblogs.com/bmbm/archive/2011/12/06/2342264.html[/url]
测试主类:
 package test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import util.JsonUtils;

/**
* 根据请求转换请求参数bean
* @author donald
* @date 2017-1-6
* @time 上午11:29:37
*/
public class RequestParamUtils {
private static final Logger log = LoggerFactory.getLogger(RequestParamUtils.class);
private static final String SET_METHOD_PREFIX = "set";
private static final String GET_METHOD_PREFIX = "get";
private static final String GETCLASS_METHOD_SUFFIX = "class";
private static SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static volatile RequestParamUtils instance = null;
public static synchronized RequestParamUtils getInstance(){
if (instance == null){
instance = new RequestParamUtils();
}
return instance;
}
/**
* 转化bean
* @param request
* @param clazz
* @return
*/

@SuppressWarnings({ "rawtypes", "unchecked" })
public T getParamBean(HttpServletRequest request, Class clazz) {
T bean = null;
try {
bean = clazz.newInstance();
} catch (InstantiationException e) {
log.error("==========请求参数模型实例化错误");
e.printStackTrace();
} catch (IllegalAccessException e) {
log.error("==========无法访问参数模型构造函数");
e.printStackTrace();
}
Method[] allGetMethodList = clazz.getMethods();
for(Method m : allGetMethodList){
if(m.getName().startsWith(GET_METHOD_PREFIX)){
if(isHaveGetProperties(clazz,m)){
log.debug("========Get Method Name:"+m.getName());
String setMethodName = SET_METHOD_PREFIX + m.getName().substring(3,m.getName().length());
log.debug("========set Method Name:"+setMethodName);
Class type = getPropertiesType(clazz,m);
if(type != null){
try {
Method setM = clazz.getMethod(setMethodName, type);
String fieldName = getMethodProperty(m);
String mProperty = request.getParameter(fieldName);
Object mobj = null;
if(mProperty != null)
mobj = ConvertStringToObject(mProperty,type);
try {
if(mobj != null)
setM.invoke(bean, mobj);
} catch (IllegalArgumentException e) {
log.error("==========参数异常");
e.printStackTrace();
} catch (IllegalAccessException e) {
log.error("==========非法访问");
e.printStackTrace();
} catch (InvocationTargetException e) {
log.error("==========目标调用异常");
e.printStackTrace();
}
} catch (SecurityException e) {
log.error("==========无访问权限");
e.printStackTrace();
} catch (NoSuchMethodException e) {
log.error("==========类中没有对应的方法:"+setMethodName);
e.printStackTrace();
}
}

}

}
}
return (T)bean;
}
/**
* 从Map转换bean
* @param params
* @param clazz
* @return
*/
@SuppressWarnings("rawtypes")
public T getParamBeanFromMap(Map params, Class clazz) {
T bean = null;
try {
bean = clazz.newInstance();
} catch (InstantiationException e) {
log.error("==========请求参数模型实例化错误");
e.printStackTrace();
} catch (IllegalAccessException e) {
log.error("==========无法访问参数模型构造函数");
e.printStackTrace();
}
Method[] allGetMethodList = clazz.getMethods();
for(Method m : allGetMethodList){
if(m.getName().startsWith(GET_METHOD_PREFIX)){
if(isHaveGetProperties(clazz,m)){
log.debug("========Get Method Name:"+m.getName());
String setMethodName = SET_METHOD_PREFIX + m.getName().substring(3,m.getName().length());
log.debug("========set Method Name:"+setMethodName);
Class type = getPropertiesType(clazz,m);
if(type != null){
try {
Method setM = clazz.getMethod(setMethodName, type);
String fieldName = getMethodProperty(m);
Object mProperty = params.get(fieldName);
try {
if(mProperty != null)
setM.invoke(bean, mProperty);
} catch (IllegalArgumentException e) {
log.error("==========参数异常");
e.printStackTrace();
} catch (IllegalAccessException e) {
log.error("==========非法访问");
e.printStackTrace();
} catch (InvocationTargetException e) {
log.error("==========目标调用异常");
e.printStackTrace();
}
} catch (SecurityException e) {
log.error("==========无访问权限");
e.printStackTrace();
} catch (NoSuchMethodException e) {
log.error("==========类中没有对应的方法:"+setMethodName);
e.printStackTrace();
}
}

}

}
}
return (T)bean;
}

/**
* clazz 是否存在m对应的属性
* @param clazz
* @param m
* @return
*/
private boolean isHaveGetProperties(Class clazz,Method m){
boolean flag = false;
String fieldName = getMethodProperty(m);
log.debug("=========Get Method Field Name:"+fieldName);
try {
if(!fieldName.equals(GETCLASS_METHOD_SUFFIX)&&!m.isAnnotationPresent(Transient.class)){
if(clazz.getDeclaredField(fieldName)!= null)
flag = true;
}
} catch (SecurityException e) {
log.error("==========无访问权限");
e.printStackTrace();
} catch (NoSuchFieldException e) {
log.error("==========类中没有对应的方法属性:"+fieldName);
e.printStackTrace();
}
return flag;
}
/**
* 获取m方法对应属性的类型
* @param clazz
* @param m
* @return
*/
@SuppressWarnings("rawtypes")
private Class getPropertiesType(Class clazz,Method m){
Class type = null;
String fieldName = getMethodProperty(m);
try {
if(!fieldName.equals(GETCLASS_METHOD_SUFFIX)){
Field f = clazz.getDeclaredField(fieldName);
type = f.getType();
log.debug(fieldName+" Type:"+type.toString());
}
} catch (SecurityException e) {
log.error("==========无访问权限");
e.printStackTrace();
} catch (NoSuchFieldException e) {
log.error("==========类中没有对应的方法属性:"+fieldName);
e.printStackTrace();
}
return type;
}
/**
* 获取方法属性名
* @param m
* @return
*/
private String getMethodProperty(Method m){
String fieldName = m.getName().substring(3,m.getName().length());
fieldName = fieldName.substring(0, 1).toLowerCase()+fieldName.substring(1, fieldName.length());
return fieldName;
}
/**
*
* @param param
* @param type
* @return
*/
@SuppressWarnings("unchecked")
private T ConvertStringToType (String param,Class type){
T obj =null;
obj = (T) param;
return obj;
}
/**
* 转化类型
* @param param
* @param type
* @return
*/
@SuppressWarnings({ "deprecation"})
private Object ConvertStringToObject(String param,Class type){
Object obj =null;
if(type.isAssignableFrom(String.class)){
obj = String.valueOf(param);
}
if(type.isAssignableFrom(Integer.class)){
obj = Integer.valueOf(param);
}
if(type.isAssignableFrom(Double.class)){
obj = Double.valueOf(param);
}
if(type.isAssignableFrom(Date.class)){
try {
obj = time.parse(param);
} catch (ParseException e) {
log.error("=========时间日期解析异常");
e.printStackTrace();
}
}
return obj;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
//从map转换bean
Map params = new HashMap();
params.put("userName", "donald");
params.put("userAge", 20);
params.put("borth", new Date());
params.put("weight", 56.3);
Param pm = new Param();
pm = RequestParamUtils.getInstance().getParamBeanFromMap(params,Param.class);
log.info("======result:"+JsonUtils.toJson(pm));

//测试类型转换方法ConvertStringToType,这种强制转化的参数设置方式,容易出现参数异常
String ss = "user";
String it = "2";
String du = "50.36";
String date = "2016-10-23 12:05:56";
// Object obj = RequestParamUtils.getInstance().ConvertStringToType(ss, String.class);
/*log.info("String:"+RequestParamUtils.getInstance().ConvertStringToType(ss, String.class));
log.info("it:"+RequestParamUtils.getInstance().ConvertStringToType(it, Integer.class));
log.info("du:"+RequestParamUtils.getInstance().ConvertStringToType(du, Double.class));
log.info("date:"+RequestParamUtils.getInstance().ConvertStringToType(date, java.util.Date.class));*/

//测试类型转换方法ConvertStringToObject,尽量用这种方式,obj实际为Class type
Object obj = RequestParamUtils.getInstance().ConvertStringToObject(ss, String.class);
log.info("String:"+RequestParamUtils.getInstance().ConvertStringToObject(ss, String.class));
log.info("it:"+RequestParamUtils.getInstance().ConvertStringToObject(it, Integer.class));
log.info("du:"+RequestParamUtils.getInstance().ConvertStringToObject(du, Double.class));
log.info("date:"+RequestParamUtils.getInstance().ConvertStringToObject(date, java.util.Date.class));
}
}


实体类:
package test;

import java.io.Serializable;
import java.util.Date;

public class Param implements Serializable{

/**
*
*/
private static final long serialVersionUID = 7834236561543851887L;
private String userName;
private Integer userAge;
private Date borth;
private Double weight;

public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
public Date getBorth() {
return borth;
}
public void setBorth(Date borth) {
this.borth = borth;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}

}


控制台输出:
2017-1-6 16:28:11 test.RequestParamUtils main
信息: ======result:{"weight":56.3,"userName":"donald","userAge":20,"borth":{"time":1483691291811,"minutes":28,"seconds":11,"hours":16,"month":0,"year":117,"timezoneOffset":-480,"day":5,"date":6}}
2017-1-6 16:28:11 test.RequestParamUtils main
信息: String:user
2017-1-6 16:28:11 test.RequestParamUtils main
信息: it:2
2017-1-6 16:28:11 test.RequestParamUtils main
信息: du:50.36
2017-1-6 16:28:11 test.RequestParamUtils main
信息: date:Sun Oct 23 12:05:56 CST 2016

你可能感兴趣的:(UTILS)