提交表单很方便,但在java中有点麻烦。
这意味着,如果有很多jsdch字段,则必须获取每个对应的值。 这样一来,代码量就会变多,其代码量就不用说了,维护也是个问题。
所以,只要传递request和实体体系对象就形成了一个很好的类。
这将得到具有值的实体类的对象
代码示例如下所示
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.Timestamp;
import Java.text.simple date format;
import javax.servlet.http.http servlet request;
公共类请求帮助器{
//*
将request请求的数据放置在java对象中
*/
publicstatictgetsinglerequest (httpservletrequestrequest,Class obj ) {
//创建实例
T instance=null;
try {
//获取类中声明的所有字段
field [ ] fields=obj.getdeclaredfields (;
//创建新的实例对象
instance=obj.newInstance (;
//利用循环
for(intI=0; i fields.length; I ) {
//获取字段的名称
String name=fields[i].getName (;
//排除序列化标识
名称. equals (serialversionuid ) ) )
连续;
}
//检索字段的类型
class type=obj.getdeclaredfield (name ).getType );
//大写首字母
string replace=name.substring (0,1 ).toUpperCase ) )
name.substring(1;
获取setter方法
methodsetmethod=obj.get method (set ' replace,type );
获取表单的所有值
stringstr=request.getparameter (replace;
if(str==null||'.equals(str ) ) }
//首字母改为小写
string small=name.substring (0,1 ).toLowerCase ) )
name.substring(1;
str=request.getparameter(small;
}
用setter方法代入对应的成员变量
if(str!=空! ' '.equals(str ) }{
//---判断要读取的数据类型
type.isassignablefrom (string.class ) }
setmethod.invoke(instance,str );
} else if (type.isassignablefrom (int.class ) ) )。
||type.isassignablefrom (integer.class ) }
setmethod.invoke(instance,integer.parseint ) (str );
} else if (type.isassignablefrom (double.class ) )。
||type.isassignablefrom (double.class ) }
setmethod.invoke(instance,double.parsedouble ) str );
}elseif(type.isassignablefrom ) Boolean.class ) )。
||type.isassignablefrom (boolean.class ) }
setmethod.invoke(Instance,Boolean.parseBoolean ) str );
} else if (type.isassignablefrom (date.class ) )
简单日期格式日期格式
= new SimpleDateFormat("yyyy-MM-dd");setMethod.invoke(instance, dateFormat.parse(str));
} else if (type.isAssignableFrom(Timestamp.class)) {
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
setMethod.invoke(instance, new Timestamp(dateFormat.parse(str).getTime()));
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//返回实体类对象
return instance;
}
}
补充知识:java反射对实体类取值和赋值,可以写成通过实体类获取其他元素的数据,很方便哦~~~
项目中需要过滤前面表单页面中传过来的实体类的中的String类型变量的前后空格过滤,由于前几天看过一个其他技术博客的的java反射讲解,非常受益。于是,哈哈哈
public static void modelTrim(T model){
Class clazz = (Class) model.getClass();
//获取所有的bean中所有的成员变量
Field[] fields = clazz.getDeclaredFields();
for(int j=0;j
//获取所有的bean中变量类型为String的变量
if("String".equals(fields[j].getType().getSimpleName())){
try {
//获取get方法名
String methodName = "get"+fields[j].getName().substring(0, 1).toUpperCase()
+fields[j].getName().replaceFirst("\w", "");
Method getMethod = clazz.getDeclaredMethod(methodName);
//打破封装
getMethod.setAccessible(true);
//得到该方法的值
Object methodValue = getMethod.invoke(model);
//判断值是否为空或者为null,非的话这过滤前后空格
if(methodValue != null && !"".equals(methodValue)){
//获取set方法名
String setMethodName = "set"+fields[j].getName().substring(0, 1).toUpperCase()
+fields[j].getName().replaceFirst("\w", "");
//得到get方法的Method对象,带参数
Method setMethod = clazz.getDeclaredMethod(setMethodName,fields[j].getType());
setMethod.setAccessible(true);
//赋值
setMethod.invoke(model, (Object)String.valueOf(methodValue).trim());
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
亲自上面试用是好使的
下面还有一套,通过request,和实体类来封装本人还未实验,以后有机会再试试
/**
* 保存数据
*@param request
*@param dto
*@throws Exception
*/
public static void setDTOValue(HttpServletRequest request, Object dto) throws Exception {
if ((dto == null) || (request == null))
return;
//得到类中所有的方法 基本上都是set和get方法
Method[] methods = dto.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
try {
//方法名
String methodName = methods[i].getName();
//方法参数的类型
Class[] type = methods[i].getParameterTypes();
//当时set方法时,判断依据:setXxxx类型
if ((methodName.length() > 3) && (methodName.startsWith("set")) && (type.length == 1)) {
//将set后面的大写字母转成小写并截取出来
String name = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
Object objValue = getBindValue(request, name, type[0]);
if (objValue != null) {
Object[] value = { objValue };
invokeMothod(dto, methodName, type, value);
}
}
} catch (Exception ex) {
throw ex;
}
}
}
以上这篇Java 通过反射给实体类赋值操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持聚米学院。