方式一、(使用流方式)
StreamAction:
package com.niit.action;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
/**
* 返回字符串
*/
public class AjaxAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private InputStream stream;
public InputStream getStream() {
return stream;
}
//set方法不需要
@Override
public String execute() throws Exception {
String str = "hello world";
stream = new ByteArrayInputStream(str.getBytes());
return SUCCESS;
}
}
struts.xml:
<pre name="code" class="html"><package name="default" namespace="/" extends="struts-default">
<action name="useStream" class="com.niit.action.StreamAction">
<result type="stream">
<param name="contentType">text/html;charset=UTF-8</param>
<param name="inputName">stream</param>
</result>
</action>
</package>
方式二、(使用struts2的json插件)
1.导包:struts2-json-plugin-2.3.15.jar
2.JsonAction:
package com.niit.action;
import com.opensymphony.xwork2.ActionSupport;
public class JsonAction extends ActionSupport {
private String message;
public String getMessage() {
return message;
}
@Override
public String execute() throws Exception {
message = "hello world";
return SUCCESS;
}
}
struts.xml:
<package name="Default" namespace="/" extends="json-default">
<action name="useJson" class="com.niit.action.JsonAction">
<result type="json"/>
</action>
</package>
方式二中jquery ajax的回调函数:
function(data){
alert(data.menssage); //data即为json数据的root,而message为json数据的key
}