怎么解析SpringMVC接受表单自动封装特性实例,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
Spring MVC中的Controller可以以实体类接受来自客户端的form表单,表单的字段自动构成实体类对象
客户端的表单
<form action="http://localhost:8080/test/user" method="POST"> <!-- 每个字段名对应实体类 --> <p> <input type="text" name="name"/> </p> <p> <input type="number" name="age"/> </p> <p> <input type="text" name="hobby"/> </p> <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"; }}
看完上述内容,你们掌握怎么解析SpringMVC接受表单自动封装特性实例的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。