用包装类型原因:Controller方法参数中定义的是基本数据类型,但是从页面提交过来的数据为null或者”"的话,会出现数据转换的异常
Controller:
@RequestMapping("/veiw") public void test(Integer age) { }Form表单:
<form action="/veiw" method="post"> <input name="age" value="5" type="text"/> ... </form>Controller中和form表单参数变量名保持一致,就能完成数据绑定,如果不一致可以使用@RequestParam注解
Model class:
public class Chapter { // 章节id private Integer id; // courseId private Integer courseId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCourseId() { return courseId; } public void setCourseId(Integer courseId) { this.courseId = courseId; } }Controller:
@RequestMapping("/veiw") public void test(Chapter chapter) { }form表单:
<form action="/veiw" method="post"> <input name="id" value="5" type="text"/> <input name="courseId" value="5" type="text"/> ... </form>只要model中对象名与form表单的name一致即可
Model class:
public Class Course{ // 课程Id private Integer courseId; // 课程名称 private String title; // 课程章节 private List<Chapter> chapterList; public Integer getCourseId() { return courseId; } public void setCourseId(Integer courseId) { this.courseId = courseId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<Chapter> getChapterList() { return chapterList; } public void setChapterList(List<Chapter> chapterList) { this.chapterList = chapterList; } }Controller:
@RequestMapping("/veiw") public void test(Course age) { }form表单:
<form action="/veiw" method="post"> <input name="chapter.id" value="5" type="text"/> <input name="chapter.courseId" value="5" type="text"/> ... </form>使用“属性名(对象类型的属性).属性名”来命名input的name
与上面的自定义复合属性差别在于input中name的命名
List,Set表单中需要指定List的下标 public Class Course{ String id; List<Chapter> chapter; setter.. getter.. }form(List、Set):
<form action="/veiw" method="post"> <input name="chapter[0].id" value="5" type="text"/> <input name="chapter[0].courseId" value="5" type="text"/> ... </form> Map <form action="/veiw" method="post"> <input name="chapter["id"] value="5" type="text"/> <input name="chapter["courseId"] value="5" type="text"/> ... </form>@RequestParam:请求参数,用于请求Url?id=xxxxxx路径后面的参数(即id) 当URL使用 Url?id=xxxxxx, 这时的id可通过 @RequestParam注解绑定它传过来的值到方法的参数上。
@RequestMapping("/book") public void findBook(@RequestParam String id) { // implementation omitted }