一、response对象返回
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("json");
out.flush();
return null;
输入结果: json
二、通过struts返回stream来输出
action代码
public class TextResult extends ActionSupport {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
publicString execute() throws Exception {
inputStream = new StringBufferInputStream("json");
return SUCCESS; }
}
xml配置
<action name="text-result" class="actions.TextResult">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
输出结果: json
三、使用struts2-json-plugin插件
action代码
public class TextResult extends ActionSupport {
private Object name;
public String execute() throws Exception {
name = "json";
return SUCCESS; }
public String getName() {
return this.name;
}
}
xml配置
<package name="example" extends="json-default">
<action name="JSONExample" class="example.JSONExample">
<result type="json">
<param name="contentType">text/html</param>
</result>
</action>
</package>
输出结果:{"name":"json"}
使用这个插件,默认会把action中所有有get方法的属性把输出,可以使用@JSON(serialize =false)这个注解进行取消。
参考strtus2文档