Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Controller
- @RequestMapping("/test")
- public class MyController {
- @InitBinder
- public void initBinder(WebDataBinder binder) {
- binder.registerCustomEditor(Date.class,
- new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
- }
- @RequestMapping(value = "/getdate", method = RequestMethod.GET)
- public @ResponseBody Date getDate(@RequestParam("dt") Date dt, Model model) {
- // dt is properly constructed here..
- return new Date();
- }
- }
- 1327682374011
- //CustomDateSerializer class
- public class CustomDateSerializer extends JsonSerializer {
- @Override
- public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws
- IOException, JsonProcessingException {
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
- String formattedDate = formatter.format(value);
- gen.writeString(formattedDate);
- }
- }
- //date getter method
- @JsonSerialize(using = CustomDateSerializer.class)
- public Date getDate() {
- return date;
- }
- <bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>
- <bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig" factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
- <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
- <property name="targetObject" ref="jacksonSerializationConfig" />
- <property name="targetMethod" value="disable" />
- <property name="arguments">
- <list>
- <value type="org.codehaus.jackson.map.SerializationConfig.Feature">WRITE_DATES_AS_TIMESTAMPS</value>
- </list>
- </property>
- </bean>
- <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
- <property name="targetObject" ref="jacksonSerializationConfig" />
- <property name="targetMethod" value="setDateFormat" />
- <property name="arguments">
- <list>
- <bean class="java.text.SimpleDateFormat">
- <constructor-arg value="yyyy-MM-dd'T'HH:mm:ssZ"/>
- </bean>
- </list>
- </property>
- </bean>
- <!-- you can't call it objectMapper for some reason -->
- <bean name="jacksonObjectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
- <property name="featuresToDisable">
- <array>
- <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS"/>
- </array>
- </property>
- </bean>
- <!-- setup spring MVC -->
- <mvc:annotation-driven>
- <mvc:message-converters register-defaults="true">
- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
- <property name="objectMapper" ref="jacksonObjectMapper"/>
- </bean>
- </mvc:message-converters>
- </mvc:annotation-driven>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement