从Struts2返回字符串结果类型

5 struts2

我想发送String作为对AJAX xhrPOST方法的响应.我正在使用Struts2来实现服务器端处理.但是,我没有得到如何将结果"type"作为字符串发送以及应该执行的映射,以便将字符串从struts2操作类发送到AJAX响应.

小智 6

您可以让action方法返回String结果,但返回StreamResult类型的结果.

换一种说法:

class MyAction {

 public StreamResult method() {
   return new StreamResult(new ByteArrayInputStream("mystring".getBytes()));
 }
}
Run Code Online (Sandbox Code Playgroud)

您不一定要从Struts2操作方法返回String.您始终可以从xwork返回Result接口的实现.

  • 可能你的意思是*返回新的StreamResult(new ByteArrayInputStream("mystring".getBytes()));*这有帮助,谢谢 (2认同)

Bri*_*ger 2

您可以通过扩展 StrutsResultSupport 非常轻松地创建一个简单的 StringResult,但据我所知,框架中没有内置任何内容。

这是我过去使用过的简单 StringResult 的实现:

public class StringResult extends StrutsResultSupport {
private static final Log log = LogFactory.getLog(StringResult.class);
private String charset = "utf-8";
private String property;
private String value;
private String contentType = "text/plain";


@Override
protected void doExecute(String finalLocation, ActionInvocation invocation)
        throws Exception {
    if (value == null) {
        value = (String)invocation.getStack().findValue(conditionalParse(property, invocation));
    }
    if (value == null) {
        throw new IllegalArgumentException("No string available in value stack named '" + property + "'");
    }
    if (log.isTraceEnabled()) {
        log.trace("string property '" + property + "'=" + value);
    }
    byte[] b = value.getBytes(charset);

    HttpServletResponse res = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);

    res.setContentType(contentType + "; charset=" + charset);
    res.setContentLength(b.length);
    OutputStream out  = res.getOutputStream();
    try {
        out.write(b);
        out.flush();
    } finally {
        out.close();    
    }
}


public String getCharset() {
    return charset;
}


public void setCharset(String charset) {
    this.charset = charset;
}


public String getProperty() {
    return property;
}


public void setProperty(String property) {
    this.property = property;
}


public String getValue() {
    return value;
}


public void setValue(String value) {
    this.value = value;
}


public String getContentType() {
    return contentType;
}


public void setContentType(String contentType) {
    this.contentType = contentType;
}
Run Code Online (Sandbox Code Playgroud)

}

我使用json 插件来做类似的事情。如果您使用它,则可以使用以下命令在操作中公开单个 String 属性:

<result name="success" type="json">
  <param name="root">propertyToExpose</param>
</result>
Run Code Online (Sandbox Code Playgroud)