Receive client form data and encapsulate it as an object

1. Define the entity class

public class UserBean {
    private Integer id ;
    private String name;
    @JsonFormat(pattern = "yyyy-MM-dd")//指定对象序列化为JSON时的日期格式
    private LocalDate birthday;
    private Integer money;
    private Double payTaxes;
}

Two, html form

<form action="http://localhost:9090/add" >
  姓名:<input type="text" name="name"><br>
  生日:<input type="text" name="birthday"><br>
  工资:<input type="text" name="money"><br>
  缴税:<input type="text" name="payTaxes"><br>
        <input type="submit" value="添加">
</form>

3. Business components

public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //将表单数据封装为用户对象
        UserBean user = new UserBean();
        System.out.println(user);
        this.fullBean(user,req);
        resp.getWriter().println(user.toString());
    }
    //
    private void fullBean(Object object,HttpServletRequest request){
        //得到表单数据的键名
        Enumeration<String> en =request.getParameterNames();
        try {
            while (en.hasMoreElements()){//判断是否有下一个元素
            //取出下一个元素
            String str = en.nextElement();
            //根据表单名,得到表单值
            String value = request.getParameter(str);
            //注意:属性名和表单名 必须一致

                //根据属性名,得到属性值
                Field f = object.getClass().getDeclaredField(str);
                f.setAccessible(true);
                //根据不同的属性类型 完成类型转换
                if(f.getType() == String.class){
                    f.set(object,value);
                } else if (f.getType() == int.class || f.getType()==Integer.class) {
                    f.set(object,Integer.parseInt(value));
                } else if (f.getType()==double.class||f.getType()==Double.class) {
                    f.set(object,Double.parseDouble(value));
                } else if (f.getType()== LocalDate.class) {
                    f.set(object,LocalDate.parse(value));
                } else if(f.getType()==String[].class){
                    f.set(object,request.getParameterValues(str));
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • getParameter() Gets the form value according to the form name. Note that when there are multiple name attributes, it takes the first value
  • getParameterValues() to get the array (you need it for checkboxes/listboxes)

Four, start

public class MainTomcat {
    public MainTomcat(){
        Tomcat tomcat = new Tomcat();
        //设置启动端口
        tomcat.setPort(9090);
        //引导http引擎
        tomcat.getConnector();
        //创建上下文对象
        Context context = tomcat.addContext("",null);
      
        //注册servlet
        Wrapper w1= Tomcat.addServlet(context,"add",new AddServlet());
        w1.setLoadOnStartup(1);
        w1.addMapping("/add");
        try {
            //启动tomcat
            tomcat.start();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        new MainTomcat();
    }
}

Guess you like

Origin blog.csdn.net/m0_74421344/article/details/130233253