一:手动封装方式
1,装备实体类
private String username;
private String password;
private String[] hobby;
public Student() {
}
public Student(String username, String password, String[] hobby) {
this.username = username;
this.password = password;
this.hobby = hobby;
}
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[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "Student{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", hobby=" + Arrays.toString(hobby) +
'}';
}
//1.根据名称获取数据
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbies = req.getParameterValues("hobby");
//2.封装bean
Student student = new Student(username,password,hobbies);
System.out.println(student);
二:反射封装方式
//根据名称获取所有参数
Map<String, String[]> map = req.getParameterMap();
//2.封装学生对象
Student student = new Student();
//2.1遍历取出数据
for (String name:map.keySet()){
String[] value = map.get(name);
try {
PropertyDescriptor pd = new PropertyDescriptor(name,student.getClass());
Method writeMethod = pd.getWriteMethod();
if (value.length>1){
writeMethod.invoke(student,(Object) value);
}else{
writeMethod.invoke(student,value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(student);
三:工具类封装方式
1,使用BeanUtils工具
//根据名称获取数据
Map<String, String[]> map = req.getParameterMap();
//2.封装学生对象
Student student = new Student();
try {
BeanUtils.populate(student,map);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(student);
System.out.println(student.getPassword());
System.out.println(student.getHobby()[0]);