SpringMVC表单和HTML表单

SpringMVC表单和HTML表单

  1. HTML表单

    1. 编写action,返回adduser.jsp

      @RequestMapping(value = "/addUser",method = RequestMethod.GET)
      public String addUser(ModelMap map){
          return "add_user";
      }
      
    2. 编写action,用于接受参数并展示

      @RequestMapping(value = "/result",method = RequestMethod.POST)
      public String result(ModelMap map, @RequestParam String name, @RequestParam int age){
          map.addAttribute("name",name);
          map.addAttribute("age",age);
          return "result";
      }
      
    3. 编写HTML表单(adduser.jsp)

      <form action="result" method="get">
          名字:<input type="text" name="name"/>
          <br>
          年龄:<input type="number" name="age"/>
          <br>
          <input type="submit">
      </form>
      
    4. 结果展示

      在这里插入图片描述

  2. SpringMVC表单

    可以自动填充或者实现一些SpringMVC提供的功能

    1. 编写实体类

      public class User {
          private String name="m";
          private int age=20;
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      }
      
    2. 编写action,返回adduser.jsp

      @RequestMapping(value = "/addUser",method = RequestMethod.GET)
      public String addUser(ModelMap map){
         User user=new User();
         user.setName("666");
         map.addAttribute("user",user);
         return "add_user";
      }
      
    3. 编写action,用于接受参数并展示

      扫描二维码关注公众号,回复: 3888990 查看本文章
      @RequestMapping(value = "/result",method = RequestMethod.POST)
      public String result(ModelMap map, @RequestParam String name, @RequestParam int age){
          map.addAttribute("name",name);
          map.addAttribute("age",age);
          return "result";
      }
      
    4. 编写SpringMVC表单(adduser.jsp)

      <form:form action="result" method="post" modelAttribute="user">
          名字:<form:input path="name"/><br>
          年龄:<form:input path="age"/><br>
          <input type="submit">
      </form:form>
      
    5. 结果展示

      在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Hi_maxin/article/details/83577198