Javabean and introspection technical details, an Introspection

Source: Internet
Author: User

Javabean and introspection technical details (transfer), javabean Introspection
1. About javabean

Javabean is a fixed java class.

The writing format is:

1) required parameter Constructors

2) attributes must be private, which is called fields.

3) provides standard getter and setter

Example: getter: String getName () settter: void setName (String name) of the name field)

Javabean example:

// The shortcut key is shift + alt + spublic class User {private String name; private int age; public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}@ Override // to facilitate printing, add a toString method public String toString () {return "User [age =" + age + ", name = "+ name +"] ";}}
Ii. About Introspection

What is introspection? : Technology for accessing javabean through reflection

In Jdk, the api: PropertyDescriptor class operates Bean attributes.

The role of introspection: we can achieve a universal

1. Access javabean in a traditional way

public class Demo1{    public static void main(String[] args)    {        User user=new User();                user.setName("zhangsan");        user.setAge(19);        System.out.println(user);    }    }

2. Access javabean via Province

Public class Demo1 {public static void main (String [] args) throws Exception {User user = new User (); // create the property descriptor PropertyDescriptor descriptor = new PropertyDescriptor ("name", User. class); // obtain the write Method writeMethod = descriptor. getWriteMethod (); // call the write method writeMethod. invoke (user, "lisi"); System. out. println (user );}}

 

3. Simplified writing to achieve versatility. Write a general method here to make the attribute name a variable. If there are many attribute names, you can retrieve the attribute names and assign values to them one by one, this is the charm of introspection.

If reflection is not needed, the traditional method cannot be universal.

The following code can assign any value to any javabean, which can only be done using the introspection method:

Import java. beans. introspectionException; import java. beans. propertyDescriptor; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import cn. itcast. day08.domain. user; public class Demo2 {/*** @ param args * @ throws IntrospectionException * @ throws InvocationTargetException * @ throws IllegalAccessException * @ throws writable */public static void main (String [] args) throws Exception {// introspection User user = new User (); setProperty (user, "name", "wangwu"); setProperty (user, "age", 11); System. out. println (user) ;}// implement a common method to assign any public static void setProperty (Object bean, String fieldName, Object value) to any attribute of a javabean) throws Exception {// create a property descriptor PropertyDescriptor descriptor = new PropertyDescriptor (fieldName, bean. getClass (); // get the write Method writeMethod = descriptor. getWriteMethod (); // call the write method writeMethod. invoke (bean, value );}}

 

Because it is especially troublesome to use in the internal environment, Apache has developed a set of APIS for operating JavaBean, which are described as follows:

 

3. BeanUtils Toolkit

Apache developed a set of APIS for operating JavaBean (introspection)

Core class BeanUtils

SetProperty (bean, name, value)

CopyProperties (target, source );

Supports conversion of basic data types from String to 8

For other referenced data types, you must register the ConvertUtils. register (Converter, Class) Converter)

 

Note: 1, to use beanutils need to import external jar package: commons-beanutils-1.8.0.jar this jar package into the lib directory

2, BeanUtils to use, but also need to import a log jar package: commons-logging.jar

Let's take a look at BeanUtils's charm:

Use BeanUtils to format a date

1. javabean

Package cn. itcast. day08.domain; import java. util. date; // whether a javabean has the name attribute depends on whether the getter or setter method is public class User {private String name; // The FIELD private int age; private Date birthday; public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public Date getBirthday () {return birthday;} public void setBirthday (Date birthday) {this. birthday = birthday;} @ Override public String toString () {return "User [name =" + name + ", age =" + age + "]";}

2. beanutils

Package cn. itcast. day08.introspector; import java. lang. reflect. invocationTargetException; import java. text. parseException; import java. text. simpleDateFormat; import java. util. date; import org. apache. commons. beanutils. beanUtils; import org. apache. commons. beanutils. convertUtils; import org. apache. commons. beanutils. converter; import org. apache. commons. beanutils. converters. dateConverter; import org. apache. commons. beanutils. locale. converters. dateLocaleConverter; import cn. itcast. day08.domain. user; public class Demo3 {public static void main (String [] args) throws Exception {User user = new User (); String name = "zhangsan "; string age = "19"; String birthday = "19801122"; // 11/22/1980 1980 11 22 // register a converter/* use an anonymous internal class to register the ConvertUtils converter. register (new Converter () {public Object convert (Class beanClass, Object value) {// String -- Date String birthday = (String) value; simpleDateFormat sdf = new SimpleDateFormat ("yyyyMMdd"); try {return sdf. parse (birthday) ;}catch (ParseException e) {return null ;}}, Date. class); */DateConverter converter = new DateConverter (); converter. setPatterns (new String [] {"yyyy-MM-dd", "yyyyMMdd", "MM/dd/yyyy"}); ConvertUtils. register (converter, Date. class); String fieldName = "name"; BeanUtils. setProperty (user, fieldName, name); BeanUtils. setProperty (user, "age", age); BeanUtils. setProperty (user, "birthday", birthday); System. out. println (user); System. out. println (user. getBirthday (). toLocaleString ());}}

 

4. WebUtils tool class

Encapsulate any form submitted by request to the corresponding javabean

 

1. User Registration jsp page:

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%> <% @ taglib prefix =" fn "uri =" http://java.sun.com/jsp/jstl/functions "%> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

2. Write a tool class and encapsulate all the parameters in the request into the javabean:

Package cn. itcast. day08.util; import java. lang. reflect. invocationTargetException; import java. SQL. date; import java. util. enumeration; import javax. servlet. http. httpServletRequest; import org. apache. commons. beanutils. beanUtils; import org. apache. commons. beanutils. convertUtils; import org. apache. commons. beanutils. converters. dateConverter; public class WebUtils {private WebUtils () {}// define a common tool and method to encapsulate the request parameters to javabean public static Object request2bean (HttpServletRequest request, Class beanClass) {try {Object bean = beanClass. newInstance (); // obtain all request parameter names Enumeration names = request. getParameterNames (); // register date converter DateConverter converter = new DateConverter (); converter. setPattern ("yyyy-MM-dd"); ConvertUtils. register (converter, Date. class); // traverse while (names. hasMoreElements () {// obtain a parameter name String name = (String) names. nextElement (); // obtain the parameter value String value = request. getParameter (name); // use the parameter name as the attribute name, and use the parameter value as the attribute value. beanutils is used to encapsulate the attribute. setProperty (bean, name, value);} return bean;} catch (Exception e) {throw new RuntimeException (e);} // The Exception must be caught and cannot be thrown to the servlet, call the exception during compilation as an exception during runtime }}

3. Write a servlet page. Check the imported package name! Relationship Identification

Package cn. itcast. day08.web. 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 cn. itcast. day08.domain. user; import cn. itcast. day08.util. webUtils; public class Servlet2 extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// parameters submitted by the form are encapsulated into javabean User bean = WebUtils. request2Bean (request, User. class); System. out. println (bean);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}

 

 

The focus of jsp is:

1. jsp running principle (will be translated into servlet)

2. jsp script expressions and script fragments

3. Nine implicit jsp objects

4. Four domain objects for web Development

5. Introspection

Use of beanUtils

Use

Related Article

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.