Without BeanUtils, the Java reflection mechanism is used: the form data is automatically encapsulated into the JavaBean

Source: Internet
Author: User

When Baidu searched for "java reflection automatically encapsulates form data to javabean", the first page displays the same code, all are implemented by importing third-party jar packages <commons-beanutils> and <commons-logging>.

I have recently studied it myself. Can I do this without using these two third-party jar packages? -------------- Yes

Note: The following code is written by myself. In order not to take up too much space, I have not pasted some automatically generated code.

Development Environment: MyEclipse 10.7Running properly on MyEclipse 2014)

Web project version: Java EE 6.0

JDK: 1.7

Tomcat server version: apache-tomcat-7.0.53

 

JSP page:

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

  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 // here only the doGet () and doPost () methods are written. Other automatically generated codes are not pasted. Please note! 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 // only the background printing demonstration is provided here. Other forwarding jumps can be supplemented by 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 tool class:

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 // pass in the className string as the parameter, just want to use reflection to implement this function
// You can also pass in Object obj as an Object. You can see that you have designed 11 public static Object getBean (HttpServletRequest request, String className) {12 try {13 // className is the JavaBean path, obtain Class14 Class c = Class. forName (className); 15 // use reflection to read the structure and create the bean Object 16 Object obj = c. getConstructor (). newInstance (); 17 // obtain the names of all form items using the request. The bean attribute names and form item names must be consistent. 18 Enumeration <String> enu = request. getParameterNames (); 19 while (enu. hasMoreElements () {20 String fieldName = enu. nextElement (); 21 // use the property name to obtain the set/get method name 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 the get Method without parameters 25 Method getMethod = c. getMethod (getMethodName, null); 26 // Obtain the corresponding set Method by using the get Method without return values (the return type of the get Method is the same as the input type of the set Method parameter) 27 Method setMethod = c. getMethod (setMethodName, getMethod. getReturnType (); 28 // enter the specific parameter value for the call and save it to the bean object. 29 String value = request. getParameter (fieldName); 30 31 // because the parameter types in the set method are different, the corresponding conversion 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 block54 e. printStackTrace (); 55} catch (IllegalAccessException e) {56 // TODO Auto-generated catch block57 e. printStackTrace (); 58} catch (IllegalArgumentException e) {59 // TODO Auto-generated catch block60 e. printStackTrace (); 61} catch (InvocationTargetException e) {62 // TODO Auto-generated catch block63 e. printStackTrace (); 64} catch (NoSuchMethodException e) {65 // TODO Auto-generated catch block66 e. printStackTrace (); 67} catch (SecurityException e) {68 // TODO Auto-generated catch block69 e. printStackTrace (); 70} 71 return null; 72} 73 74}

Running result:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.