通过JSON的方式后台数据返回到前端
程序员文章站
2022-07-12 19:11:43
...
1.Controller
/**
* 查询
* @param request
* @param response
* @return
*/
@RequestMapping(value = {"/select"}, method= RequestMethod.POST)
@ResponseBody
public String selec(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
Map resultMap = new HashMap();
try {
String code= "0";
String codes = "0";
resultMap.put("code",2);
resultMap.put("codes",5);
JSONObject json = JSONObject.fromObject(resultMap);
write(json.toString(), response);
} catch (MyException e) {
e.printStackTrace();
}
return null;
}
2.write
/**
*
* @Title: write
* @Description: 在response中输出指定的内容 ContentType为text/html;charset=UTF-8
* @param @param str
* @param @param response
* @return void 返回类型
* @throws
* @author
*/
protected void write(String str, HttpServletResponse response) {
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(str!=null?str:"");
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}