05_BeanUtils框架的使用
-
概念
- 可以将请求参数封装到java对象中
-
开发步骤
-
导包
-
代码实现
Map<String, String[]> map = request.getParameterMap(); User user = new User(); System.out.println(user); try { BeanUtils.populate(user,map); System.out.println(user); } catch (Exception e) { e.printStackTrace(); }
-
-
注意事项
- 页面上的name属性值要和java对象中的属性名一致!
06_自定义BeanUtils框架
-
代码实现
- MyBeanUtils
public class MyBeanUtils { /** * 将map集合中的请求参数值封装到对象t中 * @param t * @param map : 键:参数名称;值:一组参数值。 * @param <T> */ public static<T> void populate(T t , Map<String,? extends Object> map ){ Class<?> clazz = t.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); String methodName = "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1); System.out.println(methodName); //获取对应的set方法 try { Class<?> type = field.getType(); Method method = clazz.getMethod(methodName, type); if (null != method) { //第二个参数:请求参数的值 //id、username、password、age Object object = map.get(fieldName); if (null != object) { String[] strs = (String[]) object; if (type.getName().equals("java.lang.Integer")) { method.invoke(t,Integer.parseInt(strs[0])); } else { method.invoke(t,strs[0]); } } } } catch (Exception e) { // e.printStackTrace(); throw new MyNoSuchMethodException("field " + fieldName + " there is no setter method!!!"); } } } }
- MyNoSuchMethodException
public class MyNoSuchMethodException extends RuntimeException{ public MyNoSuchMethodException() { } public MyNoSuchMethodException(String message) { super(message); } public MyNoSuchMethodException(String message, Throwable cause) { super(message, cause); } public MyNoSuchMethodException(Throwable cause) { super(cause); } public MyNoSuchMethodException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }