BeanUtils的用法讲解
用法:用于将表单输入的内容映射到对象中
使用:
1.创建表单,注意给需要映射的内容添加name属性
<form action="servlet" method="post">
<input type="text" name="username">
<input type="text" name="pwd">
<input type="submit" value="提交" name="but" >
</form>
2.创建对象的Javabean
package Test;
public class User {
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;
}
}
3.创建servlet
package Test;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
import java.util.Map;
@WebServlet("/servlet")
public class Servlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
**//使用request.getParameterMap()获取所有表单对象**
Map<String, String[]> map = request.getParameterMap();
//创建User对象
User user = new User();
//使用BeanUtils中的populate方法,将表单对象传给user ,populate方法需要抛异常
BeanUtils.populate(user,map);
//打印获取的user
System.out.println(user.getUsername()+"..."+user.getPwd());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
需要下载的jar 包
commons-beanutils-1.9.2.jar
jackson-annotations-2.9.8.jar
jackson-core-2.9.8.jar
jackson-databind-2.9.8.jar