首页 > 代码库 > Spring MVC-Date对象的处理

Spring MVC-Date对象的处理

接收Date参数

  1. 统一日期格式,使用@InitBinder
@Controller  
public class TestController {  
      
    @RequestMapping("/test.json")  
    @ResponseBody  
    public Test testJson(Integer i, Float f, String str, Date date) {  
        Test test = new Test();  
        test.setI( i!=null ? i : 1);  
        test.setF( f!=null ? f : 2.0f);  
        test.setStr( str!=null ? str : "test");  
        test.setDate(date !=null ? date : new Date());  
        return test;  
    }  
      
    @InitBinder    
    protected void initBinder(HttpServletRequest request,  
        ServletRequestDataBinder binder) throws Exception {  
        binder.registerCustomEditor(Date.class,   
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));  
    }  
}
  1. 不同日期格式,个属性分别处理
@org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date presaleStartDate;

结合下面的配置:

<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <list>
        <!-- <bean class="com.ll.model.StringToPersonConverter" /> -->
        </list>
    </property>
</bean>

返回的Date的Json格式

  1. 单个属性处理
@com.fasterxml.jackson.annotation.JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss", timezone="CET")  
public Date getDate() {  
    return date;  
}
  1. 通过配置统一处理
<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean id="messageConverters" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="dateFormat">
                        <bean class="java.text.SimpleDateFormat">
                            <constructor-arg value="yyyy-MM-dd HH:mm:ss" />
                        </bean>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Spring MVC-Date对象的处理