如何在struts2中使用ajax以及json

 我来答
吃货的天真的家
2017-03-22 · TA获得超过108个赞
知道小有建树答主
回答量:330
采纳率:0%
帮助的人:283万
展开全部
Struts2中有两种方式处理Ajax请求:
(注:我使用的是最新的Struts 2.3.20)
1. 使用Stream result的方式以流的形式写出到客户端。(这种方式我没有亲自做实验,下面的例子参考Struts2的官方文档)
这样书写我们的Action:
package actions; import java.io.InputStream;import java.io.StringBufferInputStream;import com.opensymphony.xwork2.ActionSupport; public class TextResult extends ActionSupport { private InputStream inputStream; public InputStream getInputStream() { return inputStream; } public String execute() throws Exception { inputStream = new ByteArrayInputStream("Hello World! This is a text string response from a Struts 2 Action.".getBytes("UTF-8")); return SUCCESS; }}
这样配置我们的struts.xml:<action name="text-result" class="actions.TextResult"> <result type="stream">
们可以这样书写我们的Action:
package actions; import java.io.InputStream;import java.io.StringBufferInputStream;import com.opensymphony.xwork2.ActionSupport; public class TextResult extends ActionSupport { private InputStream inputStream; public InputStream getInputStream() { return inputStream; } public String execute() throws Exception { inputStream = new ByteArrayInputStream("Hello World! This is a text string response from a Struts 2 Action.".getBytes("UTF-8")); return SUCCESS; }}
这样配置我们的struts.xml:<action name="text-result" class="actions.TextResult"> <result type="stream">
. 使用Struts2的插件机制:(下面我以返回JSON格式的数据为例进行说明,需要struts2-json-plugin-2.3.20包,这个包在Struts2的官方下载中已经包含,不需要额外下载)
首先是前台发送Ajax请求:(我这里使用JQuery)
$("#btnClick").click(function() { $.post("hello", {name: "tanzhenyu"}, function(data) { alert(data.greeting + ", " + data.name + "!"); }, "json"); });
我们的Action这样写:
public HelloAction extends ActionSupport { private String name;//这里的nam用来接收Ajax的请求数据 private Map<String, String> resultMap;//这里的Map用来返回结果JSON数据 public getName() { return name; } public setName(String name) { this.name = name; } public getResultMap() { return resultMap; } public setResultMap(Map<String, String> resultMap) { this.resultMap = resultMap; } public String execute() { resultMap = new Map<>(); resultMap.put("greeting", "Hello"); resultMap.put("name", name); return Action.SUCCESS; }}
这里注意的是:我们的Map对象不需要手动转成JSON对象,Struts2的JSON插件会帮我们转。
我们的配置文件可以这样写:
<package name="default" namespace="/" extends="json-default"> <action name="hello" class="cn.tzy..hello.action.HelloAction"> <result type="json"> <param name="root">resultMap</param> </result> </action></package>
这里注意的是:extends必须是“json-default”,name为root的param是说明返回时被序列化的对象,值为一个OGNL表达式。
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式