JavaWeb--JavaBean and introspection

一、JavaBean

(1) What is JavaBean

JavaBean is a common java class that follows a specific writing method, and is also called a simple java object-POJO (Plain Ordinary Java Object). It is a design pattern in Java programming and a software component idea based on the Java platform.

(2) JavaBean specification

1. There is no parameter constructor

2. Privatization of member attributes

3. If the encapsulated properties need to be operated by outsiders, you must write public type setter and getter methods

4. There can be members of the get / set method, there can be no members, only get / set method. The attribute name is determined by the get / set method! Instead of member names!

(3) Why do you need to use Javabean

The benefits of using javaBean are: encapsulation, reuse, and readability !

The following quote refers to an answer:

JaveBean你可以理解为一辆货车,在你的java端和web页面进行数据传递的载体,你当然可以每个变量单独传递,或者使用集合传递,但是javabean可以使你的数据更有可读性,方便开发时明确变量的意义,也使其他阅读你代码的人能直接你的意图

如果把bean类与数据库联合使用,一张表使用bean类,可以使你的代码更加简洁高效,易于理解,现在大多数框架都会使用这种机制。

2. Overview of introspection in java

(1) What is introspection in java

Introspector (Introspector) is a set of APIs provided in Java, used to access the getter / setter methods of JavaBean properties, thereby manipulating JavaBean properties. The introspection mechanism is achieved through reflection.

(2) Why do you need introspection

The emergence of introspection is conducive to the operation of class object attributes, reducing the amount of code.

3. How to use introspection

There is a JavaBean object as follows

public class Person {
	private String name;
	private int age;
	
	public Person() {
		super();
	}

	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
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", gender=" + gender
				+ "]";
	}
}
(1) Assign a value to the name attribute in the bean object
public class Demo1 {
	
	@Test
	public void test2() throws Exception{
        //创建bean对象
		Person bean = new Person();	
		
		//利用Introspector来获取BeanInfo
		BeanInfo beanInfo = Introspector.getBeanInfo(Person.class);
		
		//利用beanInfo来获取PropertyDescriptor
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
		
		//使用PropertyDescriptor对属性进行操作
		for(PropertyDescriptor pd:pds){
			if("name".equals(pd.getName())){
				Method writeMethod = pd.getWriteMethod();
				writeMethod.invoke(bean, "张三");
				break;
			}
		}
		System.out.println(bean);
	}
}
(2) Encapsulate the Map data into the User object

User:

public class User {
	private String username;
	private String password;

	public User() {
	}
	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 String toString() {
		return "User [username=" + username + ", password=" + password + "]";
	}
}
public class Demo3 {
	@Test
	public void test() throws Exception{
		//创建bean对象
		User bean = new User();
		//创建map对象
		Map<String, String> map = new HashMap<String, String>();
		map.put("username", "张三");
		map.put("password", "123");
		
		//通过Introspector获取BeanInfo对象
		BeanInfo beanInfo = Introspector.getBeanInfo(User.class);
		//通过BeanInfo对象获取PropertyDescriptor数组
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
		//通过遍历每一个PropertyDescriptor获取相应的set/get方法,来操作属性
		for(PropertyDescriptor pd:pds){
			String name = pd.getName();		//获取标签名
			String value = map.get(name);	//获取值
			if(value != null){
				Method writeMethod = pd.getWriteMethod();
				writeMethod.invoke(bean, value);
			}
		}
		System.out.println(bean);
	}
}
(3) Use commons-beanutils to manipulate bea objects

When it comes to introspection, we must mention the tool commons-beanutils. It uses introspection at the bottom, and a lot of simplification of introspection!

Use the jar package required by beanutils:

1. commons-beanutils.jar: click to download

2. commons-logging.jar: click to download

Use BeanUtils to assign values ​​to properties

@Test
public void test() throws Exception{
	User user = new User();
			
	BeanUtils.setProperty(user, "username", "admin");
	BeanUtils.setProperty(user, "password", "admin123");	
}

Use BeanUtils to get properties

@Test
public void test() throws Exception{
	User user = new User("admin", "admin123");
		
	String username = BeanUtils.getProperty(user, "username");
	String password = BeanUtils.getProperty(user, "password");		
}

Use to encapsulate Map data into User object

@Test
public void test() throws Exception{
	Map<String,String> map = new HashMap<String,String>();
	map.put("username", "admin");
	map.put("password", "admin123");
		
	User user = new User();

	BeanUtils.populate(user, map);	
}

Note: The key in the Map must be the same as the property name of the JavaBean (ie: User class here)

(4) Encapsulation based on BeanUtils

In the method, simply pass the Class object that needs to be encapsulated map object and JavaBean object

/**
* 
* @param map:需要转换的map对象
* @param c:JavaBean的Class对象
* @return
*/
public static <T> T toBean(Map map, Class<T> c){
	try {
		//创建指定类型的JavaBean对象
		T bean = c.newInstance();
		//把数据封装到bean中
		BeanUtils.populate(bean, map);
		//返回bean对象
		return bean;
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
@Test
public void test(){
	//创建map对象
	Map<String, String> map = new HashMap<String, String>();
	map.put("username", "张三");
	map.put("password", "123");
		
	User bean = toBean(map,User.class);
	System.out.println(bean);
}

This method can be very convenient to convert map to bean object.

For example, when processing the parameters submitted by the form, you can easily convert it.

User bean = toBean(request.getParameterMap(), User.class);

Fourth, JSP and JavaBean related tags

<jsp:useBean>:创建或查询bean
	- <jsp:useBean id="user1" class="cn.itcast.domain.User" scope="session"/> 
	  在session域中查找名为user1的bean,如果不存在,创建之
    - <jsp:useBean id="user1" class="cn.itcast.domain.User" scope="session"/>
<jsp:setProperty>
    - <jsp:setProperty property="username" name="user1" value="admin"/> 
      设置名为user1的这个javabean的username属性值为admin
<jsp:getProperty>
    - <jsp:getProperty property="username" name="user1"/> 获取名为user1的javabean的名为username属性值

Novice Java, if there are errors, please correct me!

Guess you like

Origin www.cnblogs.com/Java-biao/p/12724930.html