struts1不像struts2一样,并未对json做集成,因此要使用json就必须自己写代码实现json对象的封装,可以在BaseAction中写一个共通方法,用于封装后台的数据为json对象并发送到前台:

Java代码 struts1+json的应用 _的 struts1+json的应用 _的_02
  1. public class BaseAction extends Action{
  2.  
  3. private String encoding = "UTF-8";
  4. private String contentType = "application/json";
  5.  
  6. /**
  7. * to make JSON object that will be returned to the front-end and send it
  8. *
  9. * @param response response
  10. * @param objName jsonObjectName
  11. * @param obj object that is used to make jsonObject
  12. * @throws IOException
  13. */
  14. protected void makeJSONObject(HttpServletResponse response, String objName, Object obj) throws IOException {
  15.  
  16. this.contentType = contentType + ";charset=" + encoding;
  17. LogUtil.log.info("Set contentType to: " + contentType);
  18.  
  19. JSONObject jsonObj = new JSONObject();
  20. jsonObj.put(objName, obj);
  21.  
  22. response.setContentType(contentType);
  23. response.setCharacterEncoding(encoding);
  24. PrintWriter pw = response.getWriter();
  25. pw.write(jsonObj.toString());
  26. pw.flush();
  27.  
  28. }
  29. }