返回json表达式
方法1
在action方法中使用response的api
假设在execute方法里
HttpServletResponse res = ServletActionContext.getResponse();
res.setContentType( "text/html;charset=utf-8" );
res.setHeader( "Cache-Control", "no-cache" );
res.setHeader( "Pragma", "no-cache" );
res.setDateHeader( "Expires", 0 );
JsonArray a = new JsonArray();
for (int i = 0; i <10; ++i)
a.add( new JsonPrimitive( "城市" + i ) );
res.getWriter().println( a.toString() );
然后把action的result设置为
<result/>即可
这种方法不太好因为和response api绑定了
方法2 struts2 json插件
在lib目录加入struts2-json-plugin-2.3.16.1.jar
public class Json2Action extends ActionSupport {
private String name;
private String password;
private int age;
private String ceshi;
private Shabi shabi;
public String exe() {
name = "xzc";
password = "70862045";
age = 20;
ceshi ="cs";
shabi=new Shabi();
shabi.setId( 0 );
shabi.setName( "..." );
shabi.setGrade( 2 );
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setAge(int age) {
this.age = age;
}
public String getCeshi() {
return ceshi;
}
public void setCeshi(String ceshi) {
this.ceshi = ceshi;
}
public Shabi getShabi() {
return shabi;
}
public void setShabi(Shabi shabi) {
this.shabi = shabi;
}
public int getAge() {
return age;
}
public void setPassword(String password) {
this.password = password;
}
}
<package name="jsonPkg" namespace="/json"extends="json-default">
<action name="exe" class="ssh.module3.Json2Action"method="exe">
<result type="json">
<!-- root指定json的根元素,默认会序列化整个action中有get方法的属性-->
<!-- 指定root之后就只会序列化action中的shabi属性 -->
<!--<param name="root">shabi</param>->
<!-- 跳过null -->
<!-- <paramname="excludeNullProperties">true</param> -->
<!-- 排除该属性 -->
<!-- <paramname="excludeProperties">age</param> -->
</result>
</action>
</package>
访问相关页面就会发现已经输出了json表达式了