springmvc配置的返回json java端怎么写
1个回答
展开全部
package xxx;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class ProtocolHelper {
public static void writeJSON2Response(JSONObject json,
HttpServletResponse response) throws Exception {
response.setContentType("text/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
}
public static void writeJSON2AJAXResponse(HttpServletRequest request,
JSONObject json,
HttpServletResponse response) throws Exception {
response.setContentType("text/json;charset=UTF-8");
String callback = request.getParameter("callback");
PrintWriter out = response.getWriter();
out.print(callback+"("+json+")");
out.flush();
out.close();
}
public static void writeJSON2Response(JSONArray json,
HttpServletResponse response) throws Exception {
response.setContentType("text/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
}
}
上面是返回json数据的工具类
在action中你可以使用
JSONObject json = new JSONObject();
json.put("status", "success");
ProtocolHelper.writeJSON2Response(json, response);
来向前端返回你想要传输的json数据
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询