struts1不像struts2一样,并未对json做集成,因此要使用json就必须自己写代码实现json对象的封装,可以在BaseAction中写一个共通方法,用于封装后台的数据为json对象并发送到前台:
- public class BaseAction extends Action{
- private String encoding = "UTF-8";
- private String contentType = "application/json";
- /**
- * to make JSON object that will be returned to the front-end and send it
- *
- * @param response response
- * @param objName jsonObjectName
- * @param obj object that is used to make jsonObject
- * @throws IOException
- */
- protected void makeJSONObject(HttpServletResponse response, String objName, Object obj) throws IOException {
- this.contentType = contentType + ";charset=" + encoding;
- LogUtil.log.info("Set contentType to: " + contentType);
- JSONObject jsonObj = new JSONObject();
- jsonObj.put(objName, obj);
- response.setContentType(contentType);
- response.setCharacterEncoding(encoding);
- PrintWriter pw = response.getWriter();
- pw.write(jsonObj.toString());
- pw.flush();
- }
- }