zoukankan      html  css  js  c++  java
  • 解决: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 接受前台的时间格式 传到后台的格式

  • 相关阅读:
    使用Nodejs+mongodb开发地图瓦片服务器
    深入浅出ghostbuster剖析NodeJS与PhantomJS的通讯机制
    Hibernate查询出现java.lang.IllegalArgumentException异常解决方法
    tilecache2.11在windows apache2.22安装部署
    OpenLayers调用ArcGIS Server发布的WFS服务
    无法启动ArcSDE服务
    AndroidManifest修改重打包全过程
    Java正确转换html编码
    pip 异常问题
    python 从数据库取回来的数据中文显示为乱码
  • 原文地址:https://www.cnblogs.com/zhaoyanhaoBlog/p/9379231.html
Copyright © 2011-2022 走看看