struts2 ajax 实现方式

在 struts2 中实现ajax,可以使用struts2-json-plugin扩展,但是返回的json字段必须都是Action中的属性,不可以随意的输出文本。

返回任意的文本有两种方式,

方法一:调用ServletAPI

public class HelloAction extends ActionSupport {  
    public String execute() throws Exception {  
        HttpServletResponse response = ServletActionContext.getResponse();  
        response.setCharacterEncoding("UTF-8");  
        response.setContentType("text/html; charset=utf-8");  
        PrintWriter out = response.getWriter();  
        out.print("HelloWorld");  
        out.flush();  
        out.close();  
        return NONE; // 或return null,不需要result
    }  
}  

 

这里直接获取到Servlet中的HttpServletResponse对象,通过response的输出流写一个字符串,和不使用Struts 2直接用Servlet类似。这种方式与Servlet耦合,不利于测试。

方法二:使用result type="stream"

这也是Struts 2的文档中推荐的一种方式,使用type为stream的result。通过这种方法,可以不依赖于Servlet API,所以单元测试会更方便。

   private InputStream inputstream;

    @Override
    public String execute() throws Exception {
        inputstream=new ByteArrayInputStream(returnStr.getBytes("UTF-8"));
        return SUCCESS;
    }
    <action name="ajaxReturn" class="org.apollo.action.AjaxAction" >
            <result type="stream">
                <param name="inputName">inputstream</param>    
                <param name="contentType">text/html; charset=utf-8</param>    
            </result>
        </action>

 

posted @ 2014-03-26 15:13  _流年  阅读(165)  评论(0编辑  收藏  举报