不使用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 }

    運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM