1. 程式人生 > 程式設計 >Spring MVC接受表單自動封裝特性例項解析

Spring MVC接受表單自動封裝特性例項解析

這篇文章主要介紹了Spring MVC接受表單自動封裝特性例項解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

Spring MVC中的Controller可以以實體類接受來自客戶端的form表單,表單的欄位自動構成實體類物件

客戶端的表單

<form action="http://localhost:8080/test/user" method="POST">
    <!-- 每個欄位名對應實體類 -->    
    <div>
      <input type="text" name="name"/>
    </div>

    <div>
      <input type="number" name="age"/>
    </div>

    <div>
      <input type="text" name="hobby"/>
    </div>

    <input type="submit" value="Submit"/>
</form>

實體類

public class User {
  private String name;
  private Integer age;
  private String hobby;

  public User() {
    this.name = "未初始化";
    this.age = 10;
    this.hobby = "coding";
  }

  public User(String name) {
    this.name = name;
    this.age = 10;
    this.hobby = "coding";
  }

  public User(String name,Integer age) {
    this.name = name;
    this.age = age;
    this.hobby = "coding";
  }

  public User(String name,Integer age,String hobby) {
    this.name = name;
    this.age = age;
    this.hobby = hobby;
  }

  public Integer getAge() {
    return age;
  }

  public String getHobby() {
    return hobby;
  }

  public String getName() {
    return name;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

  public void setHobby(String hobby) {
    this.hobby = hobby;
  }

  public void setName(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return "User{" +
        "name='" + name + '\'' +
        ",age=" + age +
        ",hobby='" + hobby + '\'' +
        '}';
  }
}

服務端接收

@Controller
@RequestMapping("/test")
public class TestController {

  @RequestMapping(value = "/user",method = RequestMethod.POST)
  // 控制器會自動例項化引數 
  public String user(User user) {
    System.out.println(user);
    return "redirect:/test/user";
  }

  @RequestMapping(value = "/user",method = RequestMethod.GET)
  public String user() {
    return "form";
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。