Three Methods of Manual Date Type Conversion

Manual data type conversion (converter)

  • Write custom converters, customize conversion rules, and convert date formats
    • Converter conversion interface
      • Convert one type to another type of object
      • convert()
    • Custom Converter (StringToDateConverter.java)
      • Implement the convert() method: complete the conversion of strings to java.util.Date
      • Assembling a custom ConversionService
StringToDateConverter.java source code
public class StringToDateConverter implements Converter<String, Date> {
    private String datePattern;

    public StringToDateConverter(String datePattern) {
        this.datePattern=datePattern;
    }

    @Override
    public Date convert(String dateString) {
        Date date=null;

        try {
            date=new SimpleDateFormat("yyyy年MM月dd日").parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

}
Configuration file source code
 <!-- 把字符串转为日期类型的转换器 -->
        <bean id="stringToDateConverter" class="org.springframework.context.support.ConversionServiceFactoryBean">
                <property name="converters">
                    <list>
                        <bean class="tools.StringToDateConverter" >
                            <constructor-arg type="java.lang.String" value="yyyy年MM月dd日"></constructor-arg>
                        </bean>
                    </list>
                </property>
        </bean>

        <!-- 添加了conversion-service属性之后,不再需要写@DateTimeFormat注解 -->
        <mvc:annotation-driven conversion-service="stringToDateConverter">
        </mvc:annotation-driven>
  • Custom editor to realize date format conversion
    • Assembling a custom editor with @InitBinder
      • BaseController.java, annotated @InitBinder
      • Note: Methods annotated with @InitBinder will be called when the controller is initialized.
    • Modify UserController.java to inherit BaseController
BaseController.java source code
public class BaseController {
    @InitBinder//使用注解
    public void initBinder(WebDataBinder dataBinder){
        dataBinder.registerCustomEditor(Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy年MM月dd日"), true));
    }
}
UserController.java source code
//继承就好了,不需要再做配置了
//不过个人不太推荐这样用
public class UsersController extends BaseController {
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325384543&siteId=291194637