十、BeanUtils组件(六)

一 、BeanUtils组件

1.1 引入

1.1.1 简介
	程序中对javabean的操作很频繁, 所以apache提供了一套开源的api,方便对
	javabean的操作!即BeanUtils组件。

	BeanUtils组件: 作用是简化javabean的操作!
1.1.2 使用BenUtils组件前提
	使用BenUtils组件:
			1.引入commons-beanutils-1.8.3.jar核心包
			2.引入日志支持包: commons-logging-1.1.3.jar

注意:

		需要导入两个包,一个是beanutils组件包,另外一个是日志包。
		由于beanutils组件内部以来了日志包,所以缺少日志包,会报错。
如果缺少日志jar文件,报错:

java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
	at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
	at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
	at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)

1.2 BeanUtils组件的API

	
	方法1: 设置对象的属性值
			BeanUtils.copyProperty(admin, "userName", "jack");
			BeanUtils.setProperty(admin, "age", 18);
		
			注意:
				使用BeanUtils组件设置对象的属性值时候,对于属性的类型会自动转化。
					 
					  eg:BeanUtils.copyProperty(admin, "age", "12");
					  	 BeanUtils.copyProperty(admin, "age", 12);
						
						 上面两种方式够可以给int类型的age赋值。
					     使用BeanUtils设置对象的属性值时,可以不考虑值得类型,它内部会自动转换。
					 
			
	方法2: 拷贝对象
			BeanUtils.copyProperties(newAdmin, admin);
			
			注意:使用BeanUtils组件拷贝对象时,如果对象中维护了另外一个对象,拷贝的也只是该对象的引用。
							
	
	方法3: 将map转为javaBean
			BeanUtils.populate(adminMap, map);
		
			注意:map中的key要与javabean的属性名称一致
1.2.1 设置对象的属性值
	设置对象的属性值,对于简单类型的属性,类型会自动转换。
/**
	 * 设置对象的属性
	 * 
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	private static void test1() throws IllegalAccessException, InvocationTargetException {
		//设置对象的属性
		Student s=new Student();
		
		BeanUtils.copyProperty(s, "name", "小白");
		
		//设置对象的属性值,对于简单类型的属性,类型会自动转换。
		BeanUtils.copyProperty(s, "age","12");
		//BeanUtils.copyProperty(s, "age",12);

		BeanUtils.copyProperty(s, "birth",new Date());

		System.out.println(s.getName());
		System.out.println(s.getBirth());
		
	}
1.2.2 拷贝对象
		
		 1.如果被拷贝的对象有date类型的属性时,
		 那么必须实现Date自定义类型转换器。
		 如果没有实现,那么该属性必须赋值,否则拷贝会报错。
		
		
		2.被拷贝的对象内部维护另外一个对象,拷贝时,也只是拷贝了内部维护的
		  对象的引用,即内存地址。
		

例1:被拷贝的对象由date类型的属性,没有设置自定义类型转换器,也没有赋值,拷贝时就会报错。

private static void test2() throws IllegalAccessException, InvocationTargetException {
		Student s=new Student();
		s.setName("小白");
		s.setAge(12);
		//s.setBirth(new Date());
		
		Student s2=new Student();
		
		BeanUtils.copyProperties(s2, s);
	}

在这里插入图片描述

例2:拷贝的对象内部维护另外一个对象,拷贝时,也只是拷贝了内部维护的对象的引用,即内存地址。

private static void test2() throws IllegalAccessException, InvocationTargetException {
		Student s=new Student();
		s.setName("小白");
		s.setAge(12);
		s.setBirth(new Date());
		
		User u=new User();
		u.setAge(12);
		u.setName("小黑");
		
		//学生对象中维护了用户对象。
		s.setU(u);
		
		//将s对象拷贝到s2对象
		Student s2=new Student();
		BeanUtils.copyProperties(s2, s);
		
		System.out.println(s2.getU()==u); // true
	}
1.2.3 将map转为javaBean
	private static void test3() throws IllegalAccessException, InvocationTargetException {
		
		Map map=new HashMap();
		map.put("name", "小白");
		map.put("age", "12");
		map.put("birth", new Date());
		
		//将map转换为bean
		Student s=new Student();
		BeanUtils.populate(s, map);
		
		System.out.println(s.getName());
		System.out.println(s.getBirth());
	}

1.2.4 自定义类型转换器(自定义Date类型转换器)

自定义date类型的类型转换器

private static void test4() throws IllegalAccessException, InvocationTargetException {
		
		Map map=new HashMap();
		map.put("name", "小白");
		map.put("age", "12");
		map.put("birth", "2019-01-01");
		
		//自定义date类型转换器
		ConvertUtils.register(new Converter() {
			
			@Override
			public Object convert(Class clazz, Object value) {
				
				if(value==null||"".equals(value.toString().trim())) {
					return null;
				}
				
				try {
				
					String str=(String)value;
				
					SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
				
					return sd.parse(str);
					
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				return null;
				
			}
		}, Date.class);
		
		
		//将map转化为bean
		Student s=new Student();
		BeanUtils.populate(s, map);
		
		System.out.println(s.getBirth());
	}

使用组件自带的date类型转换器

private static void test4() throws IllegalAccessException, InvocationTargetException {
		Map map=new HashMap();
		map.put("name", "小白");
		map.put("age", "12");
		map.put("birth", "2019-01-01");
		
		//使用系统自带的date类型转换器
		ConvertUtils.register(new DateLocaleConverter(), Date.class);
		
		
		//将map转化为bean
		Student s=new Student();
		BeanUtils.populate(s, map);
		
		System.out.println(s.getBirth());
	}

1.3 使用BeanUtils组件封装请求参数(BeanUtils组件的应用场景)

	获取请求参数时,我们要逐一获取,比较麻烦,
	所以可以使用BenaUtils组件,封装请求参数到实体对象。
	
	切记:实体对象的属性名一个要和表单的name名称相同。
1.3.1 使用BeanUtils组件封装请求参数(基础版本)

HelloWorld .java


public class HelloWorld  extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//String username = req.getParameter("username");
		//String pwd = req.getParameter("pwd");
		
		
		Enumeration<String> ens = req.getParameterNames();
		UserParamter userParamter=new UserParamter();
		while(ens.hasMoreElements()) {
			String key = ens.nextElement();
			String value = req.getParameter(key);
			
			try {
				BeanUtils.setProperty(userParamter, key, value);
			} catch (IllegalAccessException | InvocationTargetException e) {
				throw new RuntimeException(e);
			}
		}
		
		System.out.println("username:"+userParamter.getUsername());
		System.out.println("pwd:"+userParamter.getPwd());
	}
}

UserParamter.java 封装请求参数的实体类

public class UserParamter {
	
	private String username;
	private String pwd;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	
	<form action="${pageContext.request.contextPath}/hello" method="post">
		<input type="text"  name="username">
		<input type="text"  name="pwd">
		<input type="submit"  value="提交">
	</form>
	
</body>
</html>

浏览器访问indexjsp,并提交
在这里插入图片描述
控制台打印:
在这里插入图片描述

1.3.2 使用BeanUtils组件封装请求参数(升级版本1.2)

RequestUtil.java 封装的工具类

public class RequestUtil {

	public static <T>  T converToBean(HttpServletRequest req,Class<T> clazz) {
		
		T item=null;
		try {
			item = clazz.newInstance();
			
			Map<String, String[]> map = req.getParameterMap();
			
			BeanUtils.populate(item, map);
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		return item;
	}
}

测试:

HelloWorld .java

public class HelloWorld  extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//String username = req.getParameter("username");
		//String pwd = req.getParameter("pwd");
		
		
		UserParamter userParamter = RequestUtil.converToBean(req, UserParamter.class);
		
		System.out.println("username:"+userParamter.getUsername());
		System.out.println("pwd:"+userParamter.getPwd());
	}

}

1.3.3 使用BeanUtils组件封装请求参数(升级版本1.2)

RequestUtil.java 封装的工具类

public class RequestUtil {

	public static <T>  T converToBean(HttpServletRequest req,Class<T> clazz) {
		
		T item=null;
		try {
			item = clazz.newInstance();
			Enumeration<String> ens = req.getParameterNames();		
			while(ens.hasMoreElements()) {
				String key = ens.nextElement();
				String value = req.getParameter(key);
				
				try {
					BeanUtils.setProperty(item, key, value);
				} catch (IllegalAccessException | InvocationTargetException e) {
					throw new RuntimeException(e);
				}
			}
		} catch (InstantiationException | IllegalAccessException e1) {
			e1.printStackTrace();
		}

		return item;
	}
}

测试:

HelloWorld .java

public class HelloWorld  extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		//String username = req.getParameter("username");
		//String pwd = req.getParameter("pwd");
		
		
		UserParamter userParamter = RequestUtil.converToBean(req, UserParamter.class);
		
		System.out.println("username:"+userParamter.getUsername());
		System.out.println("pwd:"+userParamter.getPwd());
	}

}

//1. 对javabean的基本操作
@Test
public void test1() throws Exception {
	
	// a. 基本操作
	Admin admin = new Admin();

// admin.setUserName(“Jack”);
// admin.setPwd(“999”);

	// b. BeanUtils组件实现对象属性的拷贝
	BeanUtils.copyProperty(admin, "userName", "jack");
	BeanUtils.setProperty(admin, "age", 18);
	
	// 总结1: 对于基本数据类型,会自动进行类型转换!
	
	
	// c. 对象的拷贝
	Admin newAdmin = new Admin();
	BeanUtils.copyProperties(newAdmin, admin);
	
	// d. map数据,拷贝到对象中
	Admin adminMap = new Admin();
	Map<String,Object> map = new HashMap<String,Object>();
	map.put("userName", "Jerry");
	map.put("age", 29);
	// 注意:map中的key要与javabean的属性名称一致
	BeanUtils.populate(adminMap, map);
	
	// 测试
	System.out.println(adminMap.getUserName());
	System.out.println(adminMap.getAge());
}
发布了94 篇原创文章 · 获赞 0 · 访问量 625

猜你喜欢

转载自blog.csdn.net/weixin_45602227/article/details/104271642
今日推荐