首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

struts2回来json和几种方式

2012-06-27 
struts2返回json和几种方式一、response对象返回???? ??response.setContentType(text/html)?? ? ?Print

struts2返回json和几种方式

一、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文档


热点排行