@Controller @RequestMapping("/item/cat") public class ItemController {
@Autowired private ItemCatService itemCatService; @RequestMapping(value="/list",produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8") @ResponseBody public String getItemCatList(String callback) { ItemCatResult result = itemCatService.getItemCatList(); if (StringUtils.isBlank(callback)) { //需要把result转换成字符串 String json = JsonUtils.objectToJson(result); return json; } //如果字符串不为空,需要支持jsonp调用 //需要把result转换成字符串 String json = JsonUtils.objectToJson(result); return callback + "(" + json + ");"; } } |
第二种方法:
要求springmvc必须是4.1以上版本。
MappingJacksonValue
//第二种方法 @RequestMapping(value="/list") @ResponseBody public Object getItemCatList(String callback) { ItemCatResult result = itemCatService.getItemCatList(); if (StringUtils.isBlank(callback)) { //需要把result转换成字符串 return result; } //如果字符串不为空,需要支持jsonp调用 MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result); mappingJacksonValue.setJsonpFunction(callback); return mappingJacksonValue; } |