org.apache.commons.beanutils.BeanUtils
- 将HttpServletRequest中的参数封装成Bean类 ``` @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User loginUser = new User();
try {
Map<String, String[]> parameterMap = req.getParameterMap();
BeanUtils.populate(loginUser,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
- 原理
> BeanUtils.setProperty(user,"username","张三");
>
> BeanUtils.getProperty(user, "username");
User user = new User();
try {
// 会去找setUsername方法设置值
BeanUtils.setProperty(user,"username","张三");
// 会去找getUsername方法取值
String username = BeanUtils.getProperty(user, "username");
System.out.println(username);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
// User{id=0, username='张三', password='null'}
System.out.println(user.toString());
```