開發中有時候會有下面的需求,雖然不屬于常用内容,但有時候還是需要的,在這裡記錄下來,以供參考。
1、傳回檔案
@RequestMapping(“/retfile”)
public void retfile() throws IOException {
Resource resource = new ClassPathResource("/static/ueditor/ueditorConfig.json");
org.apache.commons.io.IOUtils.copy(resource.getInputStream(), response.getOutputStream());
response.flushBuffer();
}
2、傳回Jsonp
@RequestMapping(“/retjsonp”)
public void retjsonp() throws IOException {
Object object = new Object();
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(classifies);
mappingJacksonValue.setJsonpFunction(callBack);
Return mappingJacksonValue;
}
2.1 傳回JsonP内部源碼
Spring内置使用
MappingJackson2HttpMessageConverter
進行Json序列化,在
MappingJackson2HttpMessageConverter
内部可以看到。

MappingJackson2HttpMessageConverter.java檔案
3、配置傳回的Json資料
在添加
@configration
的Java類中,添加如下Bean。
@Bean
public MappingJackson2HttpMessageConverter mMappingJackson2HttpMessageConverter(){
ObjectMapper objectMapper = new ObjectMapper();
// 設定傳回日期的格式類型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(simpleDateFormat);
//傳回的JSON資料不序列化為null的内容 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(objectMapper);
return mappingJackson2HttpMessageConverter;
}