BeanUtils工具是Apache提供的一套封装数据的到javabean的工具类,使用简单方便,
常用的api:
1.向javaBean的属性设置值:
setProperty(javaBean对象,javaBean属性,javaBean属性的值);
2.获取javaBean的属性设置值:
getProperty(javaBean对象,javaBean属性);
3.向javaBean的属性设置值:
populate(javaBean对象,map对象);
注意:map对象的key(就是javaBean对象属性名称),必须和javaBean的属性名一样,才能给javaBean的属性设置值。
提交表单的数据想封装到javaBean对象里面,要求表单的name属性的值,必须和javaBean属性名称一一对应。
BeanUtils是第三方的工具,需要导入jar包。
package BeanUtils;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = 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
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package BeanUtils;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class personUtils {
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Person p = new Person();
//设置属性
BeanUtils.setProperty(p,"name","tom");
BeanUtils.setProperty(p,"age",12);
//获取属性的值
String name = BeanUtils.getProperty(p,"name");
String age = BeanUtils.getProperty(p,"age");
int i = Integer.parseInt(age);
System.out.println(name);
System.out.println(i);
//使用populate给对象赋值
Map<String,Object> map = new HashMap() ;
map.put("name","jack");
map.put("age",15);
BeanUtils.populate(p,map);
String name2 = BeanUtils.getProperty(p,"name");
String age2 = BeanUtils.getProperty(p,"age");
int i2 = Integer.parseInt(age2);
System.out.println(name2);
System.out.println(i2);
}
}
一键封装表单数据
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/bean">
<input type="text" name="name"><br>
<input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
package BeanUtils;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@WebServlet("/bean")
public class 表单封装javaBean对象 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Person p = new Person();
try {
BeanUtils.populate(p,req.getParameterMap());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
resp.getWriter().print(p);
}
}