【Java】【web】获取表单数据

获取表单数据

  • getParameter(String name) 通过名称获取表单数据

  • getParameterValues(String name) 提取复选框的方法

  • getParameterNames() 获取表单所有名称

  • getParameterMap() 获取表单提交的所有值

  • getInputStream() 获取表单字节流

  • html部分




    
    Title


姓名: 年龄: 手机号: 技能: 性别:
  • servlet部分
public class Demo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Enumeration ids = request.getParameterNames();
        while (ids.hasMoreElements()) {
            String name = (String) ids.nextElement();
            System.out.print(name + ":");
            String[] values = request.getParameterValues(name);
            for (int i = 0; i < values.length; i++) {
                System.out.println(values[i]);
            }
        }
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        System.out.println("id:" + request.getParameter("id"));
    }
}
  • 直接填充到实体类中
@WebServlet(name = "Demo")
public class Demo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
    
        TestEntity t = new TestEntity();
    
        System.out.println("封装数据前" + t);
    
        Map map = request.getParameterMap();
    
        for (Map.Entry m : map.entrySet()) {
            String name = m.getKey();
            String[] values = m.getValue();
    
            try {
                // 创建属性描述器
                PropertyDescriptor pd;
                pd = new PropertyDescriptor(name, TestEntity.class);
                // 获得setter
                Method setter = pd.getWriteMethod();
                if (values.length == 1) {
                    setter.invoke(t, values[0]);
                } else {
                    setter.invoke(t, (Object) values);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    
        }
    
        System.out.println("封装数据后:" + t);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    }
}

你可能感兴趣的:(【Java】【web】获取表单数据)