SpringMVC統一轉換null值爲空字符串的方法

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>  

重新啓動服務器後,即可看到效果。

轉換前:


轉換後:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章