Spring mvc 关于后台DATE类型接受传值的问题

Spring mvc 关于后台DATE类型接受传值的问题

  • 如果bean为的类型为 java.util.DATE这我们可以引入注解
[java]  view plain  copy
  1. @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd hh:mm:ss")  

timezone为时区 如中国:东八区 对应的就是GMT+8

pattern是转换date的规则

对前台传来的Json数据进行格式化,然后插入数据库,并且当我们从数据得到这个bean数据的时候,按照@JsonFormat对应的格式转换后传给前台。

[html]  view plain  copy
  1. $.ajax({  
  2.             url:'<%= request.getContextPath()%>/organization/saveJobDocument.do',  
  3.             data:JSON.stringify({  
  4.                 id:$("#edoc_id_text").val(),  
  5.                 documentCategory:$("#edoc_doccate_text").val(),  
  6.                 documentType:$("#edoc_doctype_text").val(),  
  7.                 documentTypeDes:$("#edoc_doctype_text option:selected").text(),  
  8.                 preriod:$("#edoc_period_text").val(),  
  9.                 receivedDate:$("#edoc_received_due").val(),  
  10.                 validDate:$("#edoc_vaild_due").val(),  
  11.                 documentNum:$("#edoc_number_text").val(),  
  12.                 documentUsage:$("#edoc_usage_text").val(),  
  13.                 documentCounty:$("#edoc_country_text").val(),  
  14.                 creditContal:$("#edoc_credit_checkbox").is(":checked")?'T':'F',  
  15.                 orginalRequest:$("#edoc_Original_checkbox").is(":checked")?'T':'F',  
  16.                 documentOwner:$("#edoc_owner_value_text").val(),  
  17.                 orgheadId:$("#edoc_settlement_group_text").val(),  
  18.                 parentId:$("#header_id_text").val()  
  19.             }),  
  20.             dataType:'json',  
  21.             contentType:"application/json",//得设置 JSON.stringify  
  22.             type:'post',  

SpringMvc 传Date类型实体对象至后台的方式

一、通过Form表单提交数据,实体对象pojo对应的字段添加注解@DateTimeFormat(pattern = "yyyy-MM-dd")

二、非Form表单,自己组织JSON格式的String提交数据,通过@RequestBody  T  接受数据。则实体对象pojo对应的字段添加注解@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8") 

此外,也可自己添加一个Convert做数据格式转换。

此外,在使用SpringMVC的时候,经常会遇到表单中的日期字符串和JavaBean的Date类型的转换,而SpringMVC默认不支持这个格式的转换,所以需要手动配置,自定义数据的绑定才能解决这个问题。 
在需要日期转换的Controller中使用SpringMVC的注解@initbinder和Spring自带的WebDateBinder类来操作。 
WebDataBinder是用来绑定请求参数到指定的属性编辑器.由于前台传到controller里的值是String类型的,当往Model里Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后再SET进去。 
代码如下:

@InitBinder  
public void initBinder(WebDataBinder binder) {  
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
    dateFormat.setLenient(false);  
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
}

或者

@InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        simpleDateFormat.setLenient(false);
        CustomDateEditor dateEditor = new CustomDateEditor(simpleDateFormat, true);
        binder.registerCustomEditor(Date.class,dateEditor);
    }

ServletRequestDataBinder 是WebDataBinder 的子类。

对于springboot 应用,上面的操作就可以了。

如果是传统的 spring xml 配置方式,需要: 
需要在SpringMVC的配置文件加上

<!-- 解析器注册 -->  
<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"/> 

换种写法

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <constructor-arg value="UTF-8"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

拓展: 
spring mvc在绑定表单之前,都会先注册这些编辑器,Spring自己提供了大量的实现类,诸如CustomDateEditorCustomBooleanEditorCustomNumberEditor等许多,基本上够用。 
使用时候调用WebDataBinderregisterCustomEditor方法 
registerCustomEditor源码:

public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) {
    getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);
}

第一个参数requiredType是需要转化的类型。 
第二个参数PropertyEditor是属性编辑器,它是个接口,以上提到的如CustomDateEditor等都是继承了实现了这个接口的PropertyEditorSupport类。 
我们也可以不使用他们自带的这些编辑器类。 
我们可以自己构造:

import org.springframework.beans.propertyeditors.PropertiesEditor;

public class DoubleEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || text.equals("")) {
            text = "0";
        }
        setValue(Double.parseDouble(text));
    }

    @Override
    public String getAsText() {
        return getValue().toString();
    }
}

参考http://www.cnblogs.com/soundcode/p/6519036.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值