struts2 直接向頁面上輸出文字
阿新 • • 發佈:2018-12-07
方法一:
以返回 stream 的方式返回原始文字字串,返回的"stream"字串必須與 struts.xml 內的 result 設定相符
// 建立私有變數 private InputStream streamActionResult = null; // struts.xml 定義返回 public InputStream getStreamActionResult() { return streamActionResult; } // action public String execute() { try { streamActionResult = new ByteArrayInputStream("success".getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // struts.xml type="stream" String strResult = "stream"; return strResult; }
struts.xml,type="stream" 與 java 內的 execute() 返回資訊一致。
<action name="message" class="net.api.APiAction" method="execute"> <result name="text" type="stream"> <param name="contentType">text/html</param> <param name="inputName">StreamActionResult</param> </result> </action>
方法二:
還有另一種採用 servlet 的方法,會更直接一些,不用修改 struts.xml,但沒有前一種方法優雅。
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// 原樣返回的字串資料
out.print(strEchostr);
out.flush();
out.close();