今天在寫代碼的時候,有一個注冊頁面regist.html,里面的表單項除了用戶名、密碼、郵箱等待,最后還有一個驗證碼。而在RegistUserServlet中用了BeanUtils來封裝成user對象。
//1.獲取數據 Map<String, String[]> map = request.getParameterMap(); //2.封裝成對象 User user=new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }
於是我就有了疑惑:request獲取的map集合中還有驗證碼這些沒用的信息,那BeanUtils.populate()方法是如何把map中的數據封裝成user的呢?不會報錯嗎?
去網上搜了一下這個方法才明白:
BeanUtils.populate( Object bean, Map properties ):
這個方法會遍歷map<key, value>中的key,如果bean中有這個屬性,就把這個key對應的value值賦給bean的屬性。
感覺java語言真的很厲害。