使用步骤
一、导包
在WEB-INF下的lib包中
导入3个包
commons-beanutils-1.9.4.jar
commons-logging-1.2.jar//beanutils是依赖logging的
commons-collections-3.2.2.jar
这里版本号要一模一样
下载详解
官网下载最新版 beanutils 所需要的 commons-beanutils-1.9.4.jar(包括 commons-logging-1.2.jar)
注意版本号要是3.2.2!!!!
commons-collections-3.2.2.jar下载连接
二、 新建实体类User
package com.qf.entity;
public class User {
private int id;
private String username;
private String password;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
三、jsp页面
<body>
<form action="/myWebProject_war_exploded/user" method="post">
用户id:<input type="text" name="id"><br/>
用户名:<input type="text" name="username"><br/>
密码:<input type="text" name="password"><br/>
手机号:<input type="text" name="phone"><br/>
<input type="submit" value="提交">
</form>
</body>
四、servlet页面
package com.qf.controller;
import com.qf.entity.User;
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(name = "UserController",value = "/user")
public class UserController 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 {
request.setCharacterEncoding("utf-8");
Map<String, String[]> map=request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getPhone());
}
}
五、运行报错
一开始忘记导入commons-logging-1.2.jar//beanutils是依赖logging的
下面图片的注释出错,应该导入的版本是commons-logging-1.2.jar!!!
六、运行报错2
java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap
没有导入commons-collections-3.2.2.jar,版本号要一样!