SpringMVC统一转换null值为空字符串的方法

转载留作备用,未亲测,转载于http://blog.csdn.net/clementad/article/details/42169049

Java Web中,如果数据库中的值为null,而不做任何转换的话,传到前端页面会显示为null,影响美观。比如,智联招聘网站上的这个样子:

在SpringMVC中,可以通过在<mvc:annotation-driven>中配置<mvc:message-converters>,把null值统一转换为空字符串,解决这个问题。下面以JSon交互的方式为例说明如何实现:

第一步:创建一个ObjectMapper

[java] view plain copy
 
  1. package com.xjj.anes.mvc.converter;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.fasterxml.jackson.core.JsonGenerator;  
  6. import com.fasterxml.jackson.core.JsonProcessingException;  
  7. import com.fasterxml.jackson.databind.JsonSerializer;  
  8. import com.fasterxml.jackson.databind.ObjectMapper;  
  9. import com.fasterxml.jackson.databind.SerializerProvider;  
  10.   
  11. /** 
  12.  * @description: 转换null对象为空字符串 
  13.  */  
  14. public class JsonObjectMapper extends ObjectMapper {  
  15.     private static final long serialVersionUID = 1L;  
  16.   
  17.     public JsonObjectMapper() {  
  18.         super();  
  19.         // 空值处理为空串  
  20.         this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {  
  21.             @Override  
  22.             public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {  
  23.                 jg.writeString("");  
  24.             }  
  25.         });  
  26.     }  
  27. }  


第二步:在SpringMVC配置文件中,把新建的ObjectMapper注入给MappingJackson2HttpMessageConverter

[html] view plain copy
 
  1. <!-- 注册RequestMappingHandlerMapping 和RequestMappingHandlerAdapter 两个bean。-->  
  2. <mvc:annotation-driven>  
  3.     <mvc:message-converters>  
  4.         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
  5.             <property name="objectMapper">  
  6.                 <bean class="com.xjj.anes.mvc.converter.JsonObjectMapper"></bean>  
  7.             </property>  
  8.         </bean>  
  9.     </mvc:message-converters>  
  10. </mvc:annotation-driven>  


重新启动服务器后,即可看到效果。

转换前:

转换后:

原文地址:https://www.cnblogs.com/jianzhixuan/p/6907228.html