浏览器请求界面
1.获取参数手动封装数据
@WebServlet("/ServletDemo4")
public class ServletDemo4 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//根据参数名获取参数值String name = req.getParameter("name");String password = req.getParameter("password");String[] hobby = req.getParameterValues("hobby");//将数据封装到学生对象中Student stu = new Student(name, password, hobby);System.out.println(stu);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}打印结果:
----------------------------------------------------------
Student{name='zhangsan', age='123', hobby=[study, game, book]}
2.通过反射封装数据
//通过反射封装数据
@WebServlet("/ServletDemo5")
public class ServletDemo5 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1.获取所有参数的信息Map<String, String[]> parameterMap = req.getParameterMap();Set<String> keys = parameterMap.keySet();//2.将数据封装到学生对象中Student stu = new Student();//遍历集合for (String key : keys) {String[] value = parameterMap.get(key);//获取学生对象的属性描述器[可以获取对应变量的相应方法]try {PropertyDescriptor pd = new PropertyDescriptor(key, stu.getClass());//获取setXxx方法;把属性名首字母变大写,加上一个set前缀,作为方法名Method method = pd.getWriteMethod();//执行方法给属性赋值;需要判断属性对应的值是否>1[]if(value.length>1){//参数个数不匹配,因此会报异常wrong number of arguements//正确的调用方法是先将String数组强制转换成Object,然后传参数method.invoke(stu,(Object)value);}else {method.invoke(stu,value);}//System.out.println(stu); 每次属性赋值都打印} catch (Exception e) {e.printStackTrace();}System.out.println(stu);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}打印结果:
----------------------------------------------------------
Student{name='zhangsan', age='123', hobby=[study, game, book]}
3.通过工具类(包)封装数据【常用】
//通过工具类(包)封装数据-
@WebServlet("/ServletDemo6")
public class ServletDemo6 extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//1.获取所有参数的信息Map<String, String[]> parameterMap = req.getParameterMap();//2.将数据封装到学生对象中Student stu = new Student();//利用BeanUtils工具类,给学生对象的属性赋值try {BeanUtils.populate(stu,parameterMap);System.out.println(stu);} catch (Exception e) {e.printStackTrace();}System.out.println(stu);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);}
}Student{name='zhangsan', age='123', hobby=[study, game, book]}
BeanUtils工具类资源