SpringMVC注解 @initbinder 解决类型转换问题

太过爱你忘了你带给我的痛 2022-01-11 03:17 412阅读 0赞

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。

使用 SpringMVC 时,常遇到表单中日期字符串和 JavaBean 的 Date 类型的转换,而 SpringMVC 默认不支持这个格式的转换,故需要手动配置,自定义数据的绑定才能解决这个问题。
在需要日期转换的 Controller 中使用 SpringMVC 的注解 @initbinder和 Spring 自带的 WebDateBinder类来操作。
WebDataBinder 是用来绑定请求参数到指定的属性编辑器.由于前端传到 controller 里的值是 String 类型的,当往 Model 里 Set这个值的时候,如果 set 的这个属性是个对象,Spring 就会去找到对应的 editor 进行转换,然后再 SET 进去。
代码如下:

  1. @InitBinder
  2. public void initBinder(WebDataBinder binder) {
  3. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  4. dateFormat.setLenient(false);
  5. binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
  6. }

需要在SpringMVC的配置文件加上

  1. <!-- 解析器注册 -->
  2. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
  3. <property name="messageConverters">
  4. <list>
  5. <ref bean="stringHttpMessageConverter"/>
  6. </list>
  7. </property>
  8. </bean>
  9. <!-- String类型解析器,允许直接返回String类型的消息 -->
  10. <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>

换种写法

  1. <mvc:annotation-driven>
  2. <mvc:message-converters>
  3. <bean class="org.springframework.http.converter.StringHttpMessageConverter">
  4. <constructor-arg value="UTF-8"/>
  5. </bean>
  6. </mvc:message-converters>
  7. </mvc:annotation-driven>

拓展:
spring mvc在绑定表单之前,都会先注册这些编辑器,Spring自己提供了大量的实现类,诸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等许多,基本上够用。
使用时候调用WebDataBinder的registerCustomEditor方法
registerCustomEditor源码:

  1. public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
  2. getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);
  3. }

第一个参数 requiredType 是需要转化的类型。
第二个参数 PropertyEditor 是属性编辑器,它是个接口,以上提到的如 CustomDateEditor 等都是继承了实现了这个接口的PropertyEditorSupport 类。
我们也可以不使用他们自带的这些编辑器类。
我们可以自己构造:

  1. import org.springframework.beans.propertyeditors.PropertiesEditor;
  2. public class DoubleEditor extends PropertyEditorSupport {
  3. @Override
  4. public void setAsText(String text) throws IllegalArgumentException {
  5. if (text == null || text.equals("")) {
  6. text = "0";
  7. }
  8. setValue(Double.parseDouble(text));
  9. }
  10. @Override
  11. public String getAsText() {
  12. return getValue().toString();
  13. }
  14. }

转自:https://www.cnblogs.com/soundcode/p/6519036.html

另一举例文章见 :SpringMvc 注解 @InitBinder 表单多对象精准绑定接收

发表评论

表情:
评论列表 (有 0 条评论,412人围观)

还没有评论,来说两句吧...

相关阅读