不使用BeanUtils,利用Java反射机制:表单数据自动封装到JavaBean

时间:2022-12-16 00:06:19

  在百度搜“java反射 将表单数据自动封装到javabean ”,第一页显示的都是一样的代码,都是利用导入第三方jar包<commons-beanutils>和<commons-logging>去实现。

  最近自己也研究的一下,不使用这两个第三方jar包,可不可以实现呢?--------------可以

说明:以下代码是我自己写的,为了不占用太多篇幅,一些自动生成的代码我没有贴上

开发环境:MyEclipse 10.7(亲测在MyEclipse 2014 上正常运行 

web project 版本:Java EE 6.0

JDK:1.7

Tomcat服务器版本:apache-tomcat-7.0.53

  JSP页面:

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

 <html>
<head>
<script type="text/javascript">
function submitForm(){
document.myForm.submit();
}
</script> </head> <body>
<form name="myForm" action="${pageContext.request.contextPath }/regServlet" method="post">
<center>
用户名:<input type="text" name="userName" value=""><br>
密码:<input type="password" name="password" value=""><br>
年龄:<input type="text" name="age" value=""><br>
工资:<input type="text" name="salary" value=""><br>
<input type="button" value="注册" onclick="submitForm()" >
</center>
</form>
</body>
</html>

  JAVABean:

 package com.it.beans;

 public class Users {
private String userName;
private String password;
private int age;
private float salary; public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
} }

  Servlet:

 package com.it.servlet;

 import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.it.beans.Users; public class RegServlet extends HttpServlet {   //这里只写了doGet()和doPost()方法,其他自动生成代码没有粘贴,请注意!
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Users user=(Users)Utils.getBean(request,"com.it.beans.Users");   //这里只做后台打印演示,其他转发跳转可自行补充
System.out.println(user.getUserName());
System.out.println(user.getPassword());
System.out.println(user.getAge());
System.out.println(user.getSalary());
} }

  Utils工具类:

 package com.it.servlet;

 import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; public class Utils {
    //传入className字符串作为参数,只是想利用反射来实现这个功能
      //也可以传入Object obj一个对象,就看自己的设计了
public static Object getBean(HttpServletRequest request, String className) {
try {
      //className为JavaBean路径,获取Class
Class c=Class.forName(className);
     //利用反射读取构造,创建bean对象
Object obj=c.getConstructor().newInstance();
     //利用request获取所有表单项name,同时规范要求bean的属性名和表单项名必须一致。
Enumeration<String> enu=request.getParameterNames();
while(enu.hasMoreElements()){
String fieldName=enu.nextElement();
         //利用属性名获取set/get方法名
String setMethodName="set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
String getMethodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
        //获取无参的get方法
Method getMethod=c.getMethod(getMethodName, null);
        //利用无参有返回值的get方法获得对应的set方法(get方法返回类型与set方法参数录入类型一致)
Method setMethod=c.getMethod(setMethodName, getMethod.getReturnType());
        //调用录入具体的参数值,保存到bean对象中。
String value=request.getParameter(fieldName);          //因为set方法中的参数类型不一样,因此要做相应的转换
32          switch (getMethod.getReturnType().getName()) {
  case "int":
  setMethod.invoke(obj, Integer.parseInt(value));
   break;
  case "float":
   setMethod.invoke(obj, Float.parseFloat(value));
  break;
  case "double":
   setMethod.invoke(obj, Double.parseDouble(value));
   break;
  case "long":
   setMethod.invoke(obj, Long.parseLong(value));
  break;
  default:
   setMethod.invoke(obj, value);
   }
          }
return obj;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 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 (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} }

    运行结果:

不使用BeanUtils,利用Java反射机制:表单数据自动封装到JavaBean不使用BeanUtils,利用Java反射机制:表单数据自动封装到JavaBean