码迷,mamicode.com
首页 > 编程语言 > 详细

Spring MVC 接受表单 自动封装特性

时间:2020-02-02 19:59:48      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:user   direct   htm   字段   form表单   客户   服务端   pre   val   

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";
    }
}

Spring MVC 接受表单 自动封装特性

标签:user   direct   htm   字段   form表单   客户   服务端   pre   val   

原文地址:https://www.cnblogs.com/esrevinud/p/12253263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!