表单提交这个方法是挺方便的,但在java来说就显得有些麻烦了,
怎么个麻烦呢,就是当你字段多的时候,你就得一个一个的获取其对应的值,这样代码量就多了起来,其代码量不说,维护也是一个问题。
所以就有了这样一个类,只需把request和实体类对象传进去就行了,
这样就会得到一个有值的实体类对象
下面是代码示例
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
public class RequestHelper {
/**
* 把request请求的数据放到java对象中
*/
public static <T> T getSingleRequest(HttpServletRequest request, Class<T> obj) {
//创建实例
T instance = null;
try {
//获取类中声明的所有字段
Field[] fields = obj.getDeclaredFields();
//创建新的实例对象
instance = obj.newInstance();
//利用循环
for (int i = 0; i < fields.length; i++) {
//获取字段的名称
String name = fields[i].getName();
//把序列化id筛选掉
if (name.equals("serialVersionUID")) {
continue;
}
//获取字段的类型
Class<?> type = obj.getDeclaredField(name).getType();
// 首字母大写
String replace = name.substring(0, 1).toUpperCase()
+ name.substring(1);
//获得setter方法
Method setMethod = obj.getMethod("set" + replace, type);
//获取到form表单的所有值
String str = 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 != null && !"".equals(str)) {
// ---判断读取数据的类型
if (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));
} else if (type.isAssignableFrom(Boolean.class)
|| type.isAssignableFrom(boolean.class)) {
setMethod.invoke(instance, Boolean.parseBoolean(str));
} else if (type.isAssignableFrom(Date.class)) {
SimpleDateFormat dateFormat = 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反射讲解,非常受益。于是,哈哈哈
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public static <T> void modelTrim(T model){
Class<T> clazz = (Class<T>) model.getClass();
//获取所有的bean中所有的成员变量
Field[] fields = clazz.getDeclaredFields();
for(int j=0;j<fields.length;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,和实体类来封装本人还未实验,以后有机会再试试
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/**
* 保存数据
*@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 通过反射给实体类赋值操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。
原文链接:https://blog.csdn.net/weixin_44578470/article/details/91355563
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-25 30
-
2025-06-04 21
-
2025-05-29 92
-
2025-05-27 21
-
2025-05-27 66
热门评论

