springmvc 1.接受日期类型的参数 2.后台返回json串的格式处理(返回json串null值处理为"")
springmvc中的配置:
<bean id="dateConvert" class="com.iomp.util.DateConvert"/> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="dateConvert"/> </set> </property> </bean> <mvc:annotation-driven conversion-service="conversionService"> <mvc:message-converters ><!--register-defaults="false"--> <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 --> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <property name="objectMapper"> <!--返回json串null值处理为""--> <bean class="com.iomp.interceptor.ObjectMappingCustomer"></bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
DateConvert类(后台接受日期类型的数据:字符串转日期类型):
package com.iomp.util; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateConvert implements Converter<String, Date> { @Override public Date convert(String stringDate) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = simpleDateFormat.parse(stringDate); } catch (ParseException e) { e.printStackTrace(); } return date; } }
ObjectMappingCustomer 类(返回json串null值处理为“”):
package com.iomp.interceptor; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; import java.io.IOException; /** * SpringMvc @responseBody 返回json串null值处理为"" */ public class ObjectMappingCustomer extends ObjectMapper { public ObjectMappingCustomer() { super(); // 允许单引号 // this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); // // 字段和值都加引号 // this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); // 数字也加引号 // this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true); // this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true); // 空值处理为空串 DefaultSerializerProvider sp = (DefaultSerializerProvider) this.getSerializerProvider(); sp.setNullValueSerializer(new JsonSerializer<Object>(){ @Override public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException { jg.writeString(""); } }); } }