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 接受前台的时间格式 传到后台的格式

  • 相关阅读:
    Visual Studio 2015编译64位MySQL Connector/C++
    html.parser无法完全解析网页之BUG的修正
    Boost-Visual studio 2015环境配置
    Struts2--拦截器和常用标签库
    Struts2---OGNL表达式和值栈的运用
    Struts2---对Servlet的API的访问,结果页面的配置,数据的封装
    Struts2---入门
    spring mvc 文件上传
    ElasticSearch 基本操作
    SpringBoot 项目打包后获取不到resource下资源的解决
  • 原文地址:https://www.cnblogs.com/zhaoyanhaoBlog/p/9379231.html
Copyright © 2011-2022 走看看