在Action中直接使用HttpServletResponse的getWriter()方法使用PrintWriter輸出;html
public class AjaxPrizeKindsAction extends ActionSupport { private Logger logger = Logger.getLogger(AjaxPrizeKindsAction.class); private IPrizeKindInfoService prizeKindInfoService; @Override public String execute() throws Exception { logger.debug("enter into AjaxPrizeKindsAction"); List<PrizeKindInfoVO> list = prizeKindInfoService.findAllByCondition(); if(list != null && list.size() > 0 ){ Object[] temp = list.toArray(); JSONArray jsonArray = JSONArray.fromObject(temp); String json = jsonArray.toString(); WebUtil.printOut(json, "text/html", "UTF-8"); }else{ String json = null; WebUtil.printOut(json, "text/html", "UTF-8"); } return null; } public void setPrizeKindInfoService(IPrizeKindInfoService prizeKindInfoService) { this.prizeKindInfoService = prizeKindInfoService; } }
WebUtil工具類:java
public class WebUtil { /** * 頁面輸出 * @param res 輸入內容 * @param contentType 內容格式,可空 * @param encoding 編碼格式,可空 * @throws Exception */ public static void printOut(String res, String contentType, String encoding) throws IOException{ PrintWriter out = null; if(contentType == null || contentType.trim().equals("")){ contentType = "text/html"; } if(encoding == null || encoding.trim().equals("")) { encoding = "UTF-8"; } logger.debug("contentType: " +contentType + " | encoding: " + encoding); try{ HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType(contentType); response.setCharacterEncoding(encoding); response.getWriter(); out = response.getWriter(); out.println(res); }catch (IOException e) { logger.error("IOException in printOut of BaseAction:", e); throw e; } finally { if(out != null) { out.flush(); out.close(); } } } }
在JSP中的AJAX請求:ajax
$.post(url, params, function (result,textStatus){ if(textStatus == 'success'){ if(result != null){ //處理result } }
struts.xml中的配置:json
<!-- ajax --> <package name="ajax" extends="struts-default" namespace="/ajax"> <action name="" class="com.test.controller.AjaxPrizeKindsAction"></action> </package>
這樣的作法是藉助工具類自定義返回流的形式,比較複雜,而且跟struts2沒有多大關係,struts2支持一種瀏覽器
stream類型的Ruselt,這種類型能夠直接向客戶端瀏覽器生成二進制響應,文本響應。ide
public class AjaxPrizeKindsAction extends ActionSupport { private Logger logger = Logger.getLogger(AjaxPrizeKindsAction.class); private InputStream inputStream; @Override public String execute() throws Exception { logger.debug("enter into AjaxPrizeKindsAction"); String a = "{\"a\":\"c\",\"sd\":\"ds\"}"; inputStream = new ByteArrayInputStream(a.toString().getBytes()); return SUCCESS; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } }
xml中的配置工具
<action name="ajaxprizekinds" class="com.shcredit.controller.prize.prizeactivity.prizeactdet.AjaxPrizeKindsAction"> <result name="success" type="stream"> <!-- 指定下載文件的文件類型 --> <param name="contentType">text/html</param> <param name="inputName">inputStream</param> </result> </action>