SpringMVC JSON

2014-11-24 09:49:28 · 作者: · 浏览: 0

在SpringMVC中使用JSON传输,还是比较容易的。

下面Spring2.5是一种方式,比较基本的。

@RequestMapping("/createData.do") 
public void createData(HttpServletResponse response) { 
 
    JSONObject json = new JSONObject(); 
    if (createDataServiceImpl.makeData() == false) { 
        json.element("isSuccess", true); 
    } else { 
        json.element("isSuccess", false); 
        json.element("errorInfo", "生成数据失败,请联系客服人员!"); 
    } 
     
    writeJSONStringToResponse(response, json.toString()); 
} 

@RequestMapping("/createData.do")
public void createData(HttpServletResponse response) {

 JSONObject json = new JSONObject();
 if (createDataServiceImpl.makeData() == false) {
  json.element("isSuccess", true);
 } else {
  json.element("isSuccess", false);
  json.element("errorInfo", "生成数据失败,请联系客服人员!");
 }
 
 writeJSONStringToResponse(response, json.toString());
}

public void writeJSONStringToResponse(HttpServletResponse response, 
            String json) { 
        response.setCharacterEncoding("utf-8"); 
        PrintWriter pw; 
        try { 
            pw = response.getWriter(); 
            pw.print(json); 
            pw.flush(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } finally{ if(pw!=null) pw.close();} 
    } 

public void writeJSONStringToResponse(HttpServletResponse response,
   String json) {
  response.setCharacterEncoding("utf-8");
  PrintWriter pw;
  try {
   pw = response.getWriter();
   pw.print(json);
   pw.flush();
  } catch (IOException e) {
   e.printStackTrace();
  } finally{ if(pw!=null) pw.close();}
 }


在Spring3.0以上可以使用 @ResponseBody注解,将Controller里返回的字串写入到Response里。

实际上3.0的方式减少了大量的代码重复。