LIFE日志php
starscream日志html
今天请求一个SpringMvc 的时候,客户端老是报出:web
The request sent by the client was syntactically incorrectspring
网上都是说的是bean的名字和表单的名字不同,可是我检查了N多遍以后,仍是有报这个异常,就想到了SpringMvc 自动装配的问题。mvc
而后看日志说是""转为int类型的时候不能够为空;ide
应该就是数据绑定的问题了,通过一番研究,springMvc的数据绑定有几种方式:spa
1,controller 独享日志
2,全局共享orm
controller独享方式: xml
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, false)); }
全局共享:
全局共享方式有几种实现方法:
①继承 WebBindingInitializer 接口来实现全局注册
使用@InitBinder只能对特定的controller类生效,为注册一个全局的customer Editor,能够实现接口WebBindingInitializer 。
public class CustomerBinding implements WebBindingInitializer { @Override public void initBinder(WebDataBinder binder, WebRequest request) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, false)); }
xml配置文件:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="net.zhepu.web.customerBinding.CustomerBinding" /> </property> </bean>
②使用conversion-service来注册自定义的converter
DataBinder实现了PropertyEditorRegistry, TypeConverter这两个interface,而在spring mvc实际处理时,返回值都是return binder.convertIfNecessary(见HandlerMethodInvoker中的具体处理逻辑)。所以能够使用customer conversionService来实现自定义的类型转换。
配置文件:
<!-- 自定义类型转换 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.cms.common.util.DateConverter" /> <bean class="com.cms.common.util.IntegerConverter" /> <bean class="com.cms.common.util.LongConverter" /> </list> </property> </bean>
实现类:
public class LongConverter implements Converter<String,Long>{ @Override public Long convert(String text) { if (StringUtil.isEmpty(text))return 0l; try { return Long.parseLong(text); } catch (Exception e) { // TODO: handle exception } return 0l; } }
xml配置converter:
<!-- 解决乱码 --> <mvc:annotation-driven conversion-service="conversionService"> <mvc:message-converters register-defaults="true"> <bean class="com.cms.common.db.UTF8StringHttpMessageConverter" /> </mvc:message-converters> </mvc:annotation-driven>