背景
在前端请求数据需要进行ajax异步请求,需要获取JSON格式的数据
方法一 使用@ResponseBody注解
但有些时候使用不了这个注解
@ResponseBody
public HashMap<String,String> modelTest(HttpServletRequest request, HttpServletResponse response){
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("msg","Hello other");
hashMap.put("payMeant","false");
return hashMap;
}
方法二 使用标准的返回值ModelAndView
public ModelAndView getPayDesc(HttpServletRequest request, HttpServletResponse response){
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("contractName","添加数据");
hashMap.put("contractPrice","12.80");
hashMap.put("desc",desc);
ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView()).addAllObjects(hashMap);
return modelAndView;
}
方法三 使用流返回
public void getPayDesc(HttpServletRequest request, HttpServletResponse response){
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("contractName","添加数据");
hashMap.put("contractPrice","12.80");
hashMap.put("desc",desc);
String jsonString = JSONObject.toJSONString(hashMap);
//流返回
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
writer.println(jsonString);
}