详解SpringMVC注解@initbinder解决类型转换问题
在使⽤SpringMVC的时候,经常会遇到表单中的⽇期字符串和JavaBean的Date类型的转换,⽽SpringMVC默认不⽀持这个格式的转换,所以需要⼿动配置,⾃定义数据的绑定才能解决这个问题。
在需要⽇期转换的Controller中使⽤SpringMVC的注解@initbinder和Spring⾃带的WebDateBinder类来操作。
WebDataBinder是⽤来绑定请求参数到指定的属性编辑器.由于前台传到controller⾥的值是String类型的,当往Model⾥Set这个值的时候,如果set的这个属性是个对象,Spring就会去到对应的editor进⾏转换,然后再SET进去。
代码如下:
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
}
需要在SpringMVC的配置⽂件加上
<!-- 解析器注册 -->
spring framework表达式assign
<bean class="org.springframework.web.hod.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringHttpMessageConverter"/>
</list>
</property>
</bean>
<!-- String类型解析器,允许直接返回String类型的消息 -->
<bean id="stringHttpMessageConverter" class="org.verter.StringHttpMessageConverter"/>
换种写法
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.verter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
拓展:
spring mvc在绑定表单之前,都会先注册这些编辑器,Spring⾃⼰提供了⼤量的实现类,诸如CustomDateEditor
,CustomBooleanEditor,CustomNumberEditor等许多,基本上够⽤。
使⽤时候调⽤WebDataBinder的registerCustomEditor⽅法
registerCustomEditor源码:
public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);
}
第⼀个参数requiredType是需要转化的类型。
第⼆个参数PropertyEditor是属性编辑器,它是个接⼝,以上提到的如CustomDateEditor等都是继承了实现了这个接⼝的PropertyEditorSupport类。
我们也可以不使⽤他们⾃带的这些编辑器类。
我们可以⾃⼰构造:
import org.springframework.beans.propertyeditors.PropertiesEditor;
public class DoubleEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.equals("")) {
text = "0";
}
setValue(Double.parseDouble(text));
}
@Override
public String getAsText() {
return getValue().toString();
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。