参数绑定
- spring参数绑定过程
从客户端请求key/value数据,经过参数绑定。将key/value的数据绑定到controller方法的形参上
springmvc中,接收页面提交的数据是通过方法形参来接收,而不是定义成员变量来接收
- 参数绑定默认支持的类型
直接在controller方法形参上定义下边的类型,就可以使用这些对象,在参数绑定的
过程中,如果遇到下边类型直接进行绑定
HttpServletRequest
HttpServletResponse
HttpSession
ModelMap
将模型数据填充到request域
简单类型:
通过RequestParam对简单参数进行绑定,如果不使用,要求request和controller方法的形参名一致才能绑定成功
Integer id
itemsService.updateItems(id, itemsCustom);
- 如果使用注解,不用限制
public String editItems(Model model,@RequestParam(value="id",required = true)Integer items_id) throws Exception{
- 绑定pojo
页面中input的name和controller的pojo形参中的属性名一致,将页面中的数据绑定到pojo,页面的定义,pojo属性名定义一致
- 注意:post乱码问题:
在web.xml中添加乱码过滤器
<!-- 乱码过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
自定义参数绑定实现日期
对于controller形参中pojo对象,如果属性中有日期类型,需要自定义参数绑定,将请求的日期的数据串转成日期类型,要转换的日期类型和pojo中日期属性的类型保持一致,自定义参数绑定转换成util
需要向处理器适配器中注入自定义的参数绑定组件
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<bean id ="conversionService" class ="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class = "com.shagou.ssm.controller.converter.CustomDateConvertor"/>
</list>
</property>
</bean>
public class CustomDateConvertor implements Converter<String,Date>{
@Override
public Date convert(String source) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
//转成直接返回
return simpleDateFormat.parse(source);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//转换失败返回null
return null;
}
}