springmvc有时会在页面中出现400问题,这个时候查看所有的流程,发现没什么问题,但就是访问不到controller,页面400依旧。此时大多数原因是springmvc的数据封装问题。
也就是说,springmvc不能将你从前台传过来的数据封装到实体类中,就报了这个异常,比如说,你实体类有个Date类型数据,前台输入一个日期字符串,就会出现400,因为springmvc不能将String数据转换成Date类型,需要自己自己定义转换器或者更改数据类型,如果实体类中有个int类型数据,前台传入一个大于int范围的数据,也会出现400问题,并且后台也没有异常报出,比较烦恼。网上搜了篇文章,关于自定义转换器的使用。
http://my.oschina.net/Tonyjingzhou/blog/264364
主要内容摘抄了过来:
springmvc数据转换方式:
1,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));
}
2,全局共享
2.1继承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));
}
spring或者springmvc配置文件中配置
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean
class="net.zhepu.web.customerBinding.CustomerBinding" />
</property>
</bean>
2.2使用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;
}
}
springmvc中配置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>