(1)基本数据类型(比如int)
@RequestMapping(value="test.html",method="post")
public void test(int age) {
......
}
使用这种方式要求表单中需要提交的数据,这里指年龄的name属性需要满足和参数中变量名称一致:
<form method = "post" action="test.html">
<input name = 'age' type = "number" />
......
</form>
需要注意如果表单提交的数据为null或""时,提交到服务端则会出现异常。因此,如果想采用这种方式并且需要提交的数据可能为空,则建议使用简单类型的包装类型!即采用下面方式:
@RequestMapping(value="test.html",method="post")
public void test(Integer age) {
......
}
(2)自定义的java pojo
@Getter
@Setter
public class User {
private String username;
private String password;
private String email;
}
自定义一个pojo,这里使用了lombox的@Setter和@Getter注解,可以自动生成get和set方法。
后端接收代码:
@RequestMapping(value = "addUser.html",method="post")
public void addUser(User user){
......
}
前端代码,前面的基本类型类似
<form method ="post" action = "/addUser.html">
<input type ="text" name = "username" />
<input type ="password" name = "password" />
<input type ="email" name = "email" />
<input type ="submit" value ="提交">
</form>
如果User里包含其他自定义类型Address
@Getter
@Setter
public class User {
private String username;
private String password;
private String email;
private Address address;
}
public class Address{
private String country;
private String city;
}
前端只需要使用.指定内层名称
<form method ="post" action = "/addUser.html">
<input type ="text" name = "username" />
<input type ="password" name = "password" />
<input type ="email" name = "email" />
<input type ="text" name="address.country"/>
<input type ="text" name="address.city" />
<input type ="submit" value ="提交">
</form>
(3)List、Set和Map类型
这种情况直接在表单直接提交比较少了(大都采用ajax的方式),处理方式和上述的Address类型,只是分别对应的对象类型变了,但是一定要将需要提交的List活着Set包装在一个pojo中去提交,以个人电话为例
@Getter
@Setter
public class User {
private String username;
private String password;
private String email;
private List<Phone> phones;
}
public class Phone{
private String number;
private Integer type;
}
后端代码都是一样的
@RequestMapping(value = "addUser.html",method="post")
public void addUser(User user){
......
}
前端代码例子
<form method ="post" action = "/addUser.html">
<input type ="text" name = "username" />
<input type ="password" name = "password" />
<input type ="email" name = "email" />
<input type ="text" name="phone[0].number"/>
<input type ="number" name="phone[0].type" />
<input type ="text" name="phone[1].number"/>
<input type ="number" name="phone[1].type" />
<input type ="submit" value ="提交">
</form>
Set和上述类似,Map类型和上述的区别在于不是用索引,如果Map里保存的简单类型那么phone['key1'],phone["key2"]这种格式,如果是复合类型则phone['key1'].xxx,phone['key1'].yyy,phone["key2"].xxx,phone["key2"].yyy
网友评论