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

  在百度搜“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页面:

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 
 3 <html>
 4 <head>
 5 <script type="text/javascript">
 6         function submitForm(){
 7             document.myForm.submit();
 8         }
 9     </script>
10 
11 </head>
12   
13   <body>
14     <form name="myForm" action="${pageContext.request.contextPath }/regServlet" method="post"> 
15     <center>
16     用户名:<input type="text" name="userName" value=""><br>
17     密码:<input type="password" name="password" value=""><br>
18     年龄:<input type="text" name="age" value=""><br>
19     工资:<input type="text" name="salary" value=""><br>
20     <input type="button" value="注册" onclick="submitForm()" >
21     </center>
22     </form>
23   </body>
24 </html>

  JAVABean:

 1 package com.it.beans;
 2 
 3 public class Users {
 4     private String userName;
 5     private String password;
 6     private int age;
 7     private float salary;
 8     
 9     public String getUserName() {
10         return userName;
11     }
12     public void setUserName(String userName) {
13         this.userName = userName;
14     }
15     public String getPassword() {
16         return password;
17     }
18     public void setPassword(String password) {
19         this.password = password;
20     }
21     public int getAge() {
22         return age;
23     }
24     public void setAge(int age) {
25         this.age = age;
26     }
27     public float getSalary() {
28         return salary;
29     }
30     public void setSalary(float salary) {
31         this.salary = salary;
32     }
33     
34 }

  Servlet:

 1 package com.it.servlet;
 2 
 3 import java.io.IOException;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.http.HttpServlet;
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletResponse;
 8 
 9 import com.it.beans.Users;
10 
11 public class RegServlet extends HttpServlet {
12 
13   //这里只写了doGet()和doPost()方法,其他自动生成代码没有粘贴,请注意!
14    public void doGet(HttpServletRequest request, HttpServletResponse response)
15             throws ServletException, IOException {
16 
17         this.doPost(request, response);
18     }
19    public void doPost(HttpServletRequest request, HttpServletResponse response)
20             throws ServletException, IOException {
21         request.setCharacterEncoding("UTF-8");
22         Users user=(Users)Utils.getBean(request,"com.it.beans.Users");
23 
24       //这里只做后台打印演示,其他转发跳转可自行补充
25         System.out.println(user.getUserName());
26         System.out.println(user.getPassword());
27         System.out.println(user.getAge());
28         System.out.println(user.getSalary());
29     }    
30     
31 }

  Utils工具类:

 1 package com.it.servlet;
 2 
 3 import java.lang.reflect.InvocationTargetException;
 4 import java.lang.reflect.Method;
 5 import java.util.Enumeration;
 6 
 7 import javax.servlet.http.HttpServletRequest;
 8 
 9 public class Utils {
10     //传入className字符串作为参数,只是想利用反射来实现这个功能
      //也可以传入Object obj一个对象,就看自己的设计了 11 public static Object getBean(HttpServletRequest request, String className) { 12 try { 13       //className为JavaBean路径,获取Class 14 Class c=Class.forName(className); 15      //利用反射读取构造,创建bean对象 16 Object obj=c.getConstructor().newInstance(); 17      //利用request获取所有表单项name,同时规范要求bean的属性名和表单项名必须一致。 18 Enumeration<String> enu=request.getParameterNames(); 19 while(enu.hasMoreElements()){ 20 String fieldName=enu.nextElement(); 21          //利用属性名获取set/get方法名 22 String setMethodName="set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1); 23 String getMethodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1); 24         //获取无参的get方法 25 Method getMethod=c.getMethod(getMethodName, null); 26         //利用无参有返回值的get方法获得对应的set方法(get方法返回类型与set方法参数录入类型一致) 27 Method setMethod=c.getMethod(setMethodName, getMethod.getReturnType()); 28         //调用录入具体的参数值,保存到bean对象中。 29 String value=request.getParameter(fieldName); 30 31          //因为set方法中的参数类型不一样,因此要做相应的转换 32          switch (getMethod.getReturnType().getName()) { 33   case "int": 34   setMethod.invoke(obj, Integer.parseInt(value)); 35    break; 36   case "float": 37    setMethod.invoke(obj, Float.parseFloat(value)); 38   break; 39   case "double": 40    setMethod.invoke(obj, Double.parseDouble(value)); 41    break; 42   case "long": 43    setMethod.invoke(obj, Long.parseLong(value)); 44   break; 45   default: 46    setMethod.invoke(obj, value); 47    }
          }
48 return obj; 49 } catch (ClassNotFoundException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } catch (InstantiationException e) { 53 // TODO Auto-generated catch block 54 e.printStackTrace(); 55 } catch (IllegalAccessException e) { 56 // TODO Auto-generated catch block 57 e.printStackTrace(); 58 } catch (IllegalArgumentException e) { 59 // TODO Auto-generated catch block 60 e.printStackTrace(); 61 } catch (InvocationTargetException e) { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 } catch (NoSuchMethodException e) { 65 // TODO Auto-generated catch block 66 e.printStackTrace(); 67 } catch (SecurityException e) { 68 // TODO Auto-generated catch block 69 e.printStackTrace(); 70 } 71 return null; 72 } 73 74 }

    运行结果:

 

posted @ 2014-05-23 09:56  夜空下的流星  阅读(3328)  评论(6编辑  收藏  举报