springmvc配置时间转换器

第一种:局部配置

1、使用配置方式:

在需要接受Date参数的Controller实现接口WebBindingInitializer,实现方法initBinder(WebDataBinder binder, WebRequest request)

@Controller
public class UserController implements WebBindingInitializer {

    @Autowired
    UserService userService;
    
    @RequestMapping("/test/springmvc.do")
    public String test(String name, Date birthday){
        System.out.println(birthday);
        return "success";
    }
    //转换日期格式
   @Override
    public void initBinder(WebDataBinder binder, WebRequest request){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

2、使用注解方式:

加上注解@InitBinder

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/test/springmvc.do")
    public String test(String name, Date birthday){
        System.out.println(birthday);
        return "success";
    }
    //转换日期格式
    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

第二种:全局配置

实现Converter接口

public class CustomDateEdtor implements Converter<String, Date> {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Date convert(String s) {
        Date date = null;
        try {
            date = sdf.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}

在springMVC-servlet.xml中配置

<!--把转换器对象注入SpringMVC转换器工厂中-->
<bean id="conversionServiceFactory" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.ice.web.CustomDateEdtor"/>
        </set>
    </property>
</bean>
<!--开启注解驱动-->
<mvc:annotation-driven conversion-service="conversionServiceFactory"/>
posted @ 2021-05-30 15:35  icefield817  阅读(192)  评论(0编辑  收藏  举报