您的位置:首页 > 编程语言 > Java开发

SpringMvc 数据绑定400错误

2014-05-13 18:53 387 查看
今天请求一个SpringMvc 的时候,客户端总是报出:
The request sent by the client was syntactically incorrect
网上都是说的是bean的名字和表单的名字不一样,但是我检查了N多遍之后,还是有报这个异常,就想到了SpringMvc 自动装配的问题。
然后看日志说是""转为int类型的时候不可以为空;
应该就是数据绑定的问题了,经过一番研究,springMvc的数据绑定有几种方式:
1,controller 独享
2,全局共享

controller独享方式:

@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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐