解决:springmvc中接收date数据问题

这里提供三种解决方案。 

一.局部转换 :只是对当前Controller类有效

springMVC.xml中添加:

  <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringHttpMessageConverter" />
            </list>
        </property>
    </bean>
    <!-- String类型解析器,允许直接返回String类型的消息 -->
    <bean id="stringHttpMessageConverter"
        class="org.springframework.http.converter.StringHttpMessageConverter" /> 
    <!-- 日期转换 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="com.rw.tools.ConvertDate"/>
        </property>
    </bean>
Controller 类文件中添加:
@Controller
@RequestMapping("/image")
public class ImageController {
    
    @Autowired
    private ImageService imageService;
    
    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder binder){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        CustomDateEditor dateEditor = new CustomDateEditor(df, true);
        binder.registerCustomEditor(Date.class,dateEditor);
    }

二.全局转换

1.创建convertDate类实现WebBindingInitializer接口

public class convertDate implements WebBindingInitializer{
 
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // TODO Auto-generated method stub
        //转换日期
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}

2.在Spring-MVC.xml中配置日期转换

<!-- 日期转换 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="webBindingInitializer">
            <bean class="com.wx.web.convertDate"/>
        </property>
    </bean>

三.实体类属性方法配置 

 @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")//接受前台的时间格式 传到后台的格式
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")//作用:后台的时间 格式化 发送到前台
    private Date date;

@JsonFormat 默认是标准时区的时间, 北京时间 东八区 timezone=”GMT+8” 
作用:后台的时间 格式化 发送到前台

@DateTimeFormat 接受前台的时间格式 传到后台的格式

原文地址:https://www.cnblogs.com/zhaoyanhaoBlog/p/9379231.html