什么是数据绑定?
例子1:
@ResponseBody 注解直接返回字符串到客户端,不需要返回 jsp 页面。
@RequestMapping(value="/baseType")
@ResponseBody
public String baseType(int id){
return "id:"+id;
}
测试,HTTP 请求不带参数,直接报 500 错误。
可选的参数“id”不能转为 null,因为我们都知道,基本数据类型不能赋值 null。
测试:参数类型为字符串。
400 错误,错误原因:
String 类型不能转换为 int 类型。
例子2:
@RequestMapping(value="/packageType")
@ResponseBody
public String packageType(Integer id){
return “id:”+id;
}
测试:不传参数。
没有报错,直接打印 null,因为包装类可以赋值 null。
测试:参数类型为字符串。
400 错误,错误原因:
String 类型不能转换为 Integer 类型。
例子3
@RequestMapping(value="/packageType")
@ResponseBody
public String packageType(@RequestParam(value="id",required=false,defaultValue="1") Integer id){
return "id:"+id;
}
value=“id”:将 HTTP 请求中名为 id 的参数与形参进行映射。
required=false:id 参数非必填,可省略。
defaultValue=“1”:若 HTTP 请求中没有 id 参数,默认值为1。
测试例子
例子4
@RequestMapping(value="/packageType")
@ResponseBody
public String packageType(@RequestParam(value="id",required=true) Integer id){
return "id:"+id;
}
报错,因为 id 为必填参数,此时客户端没有传 id 参数,同时业务方法中 id 也没有默认值,所以报错。
若客户端传 id 或者 id 有 dafaultValue,程序不会报错。
例子5
PoJo
(1)创建 User 类
public class User {
private String name;
private int age;
}
(2)JSP 页面 input 标签的 name 值与实体类的属性名对应。
<form action="pojoType" method="post">
姓名:<input type="text" name="name"/><br/>
年龄:<input type="text" name="age"/><br/>
<input type="submit" value="提交"/>
</form>
(3)业务方法
@RequestMapping(value="/pojoType")
@ResponseBody
public String pojoType(User user){
return "注册用户信息:"+user;
}
运行
处理 @ResponseBody 中文乱码:在 springmvc.xml 中配置消息转换器。
<mvc:annotation-driven >
<!-- 消息转换器 -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
例子6
例子7
例子8
Map