- 前言
读完本文将会学到以下内容:
- 基本数据类型和包装类的参数绑定
学习本文需要安装的软件:
- JDK1.8 、IDEA2017.3、Maven3.3.3、Tomcat7.0.64
- 基本数据类型和包装类的参数绑定
1.准备POJO
public class TestUser {
private Integer id;
private String name;
//get,set方法
}
2.测试代码
//参数绑定:基本数据类型和包装类
//测试URL--http://localhost:8080/params1.test?id=23&name=xiaoming
@RequestMapping(value = "/params1.test")
public void bindParams1(int id, String name) {
System.out.println("id=" + id); //id=23
System.out.println("name=" + name); //name=xiaoming
}
3.注意事项
3.1 URL中的属性名要与方法中的形参名相同,如果不相同可以使用注解@RequestParam。
例如:
- 访问URL为 http://localhost:8080/params1.test?id=23&username=xiaoming ,则代码应添加注解@RequestParam。
@RequestMapping(value = "/params1.test")
public void bindParams1(int id, @RequestParam(value="username") String name) {
System.out.println("id=" + id); //id=23
System.out.println("name=" + name); //name=xiaoming
}
3.2 URL携带的属性值默认是字符串。如果属性值是数字可以当成整型或浮点型。
例如:
- 访问URL为 http://localhost:8080/params1.test?id=23&name=xiaoming ,23可以当成整型,bindParams1方法中的形参id被赋值为23。
但是但是
- 如果:访问URL为 http://localhost:8080/params1.test?id=&name=xiaoming 或 http://localhost:8080/params1.test?id&name=xiaoming,bindParams1方法中的形参id被赋值为空串”“,空串想转为int型,代码报错。
- 如果:访问URL为 http://localhost:8080/params1.test?name=xiaoming,bindParams1方法中的形参id被赋值为null,null想转为int型,代码报错。
解决办法:使用包装类Integer来接收空串和null。
- 后记
下文将会介绍以下内容: