1. 程式人生 > >SpringMVC表單和HTML表單

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,用於接受引數並展示

      @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. 結果展示

      在這裡插入圖片描述