Struts2 JSON

来源:互联网 发布:淘宝代销好做吗 编辑:程序博客网 时间:2024/05/08 17:11

Struts2 JSON

在action中返回JOSN数据。具体过程可以参考油管的视频Ajax and JSON In Struts 2。
主要使用的是JSON Plugin插件。文档见[JSON Plugin] (https://struts.apache.org/docs/json-plugin.html),这儿有翻译Struts2-Json-Plugin 的使用(翻译自官方文档)

在lib中加入struts2的struts2-json-plugin-2.3.28.jar包。
合起来,struts2需加入的包如下:
这里写图片描述

例子说明

新建一个AjaxController类,继承自ActionSupport

返回一个字符串

在test.jsp中添加一个按钮,给按钮绑定ajax事件,在div中显示ajax获取的结果

<form>    <input type="button" value="Hello" class="buttonhello"></form><div class="result"></div>

AjaxController中,定义一个名为hello的方法,该方法在response中,返回Hello Ajax字符串

public void hello(){    try {        HttpServletResponse response = ServletActionContext.getResponse();        response.setContentType("text/plain;charset=utf-8");        PrintWriter out = response.getWriter();        out.println("Hello Ajax");        out.flush();    } catch (Exception e) {    }}

配置struts.xml文件,如下

    <!-- 测试Ajax  -->    <package name="default" namespace="/" extends="struts-default">        <action name="hello" class="test.AjaxController" method="hello">        </action>    </package>

给按钮绑定ajax请求事件:

    $('.buttonhello').click(function(){        $.ajax({            type:'GET',            url:'${pageContext.request.contextPath}/hello.action',            success: function(response){                $('.result').html(response);            }        })    })

可以发现在点击hello按钮后,界面显示如下的结果:
结果

返回两个变量相加的结果

AjaxController中,添加类型为int的a,b两个变量,并添加一个名为sum的方法,返回的是a+b的值,如下:

private int a;private int b;public int getA() {    return a;}public void setA(int a) {    this.a = a;}public int getB() {    return b;}public void setB(int b) {    this.b = b;}public void sum(){    try {        HttpServletResponse response = ServletActionContext.getResponse();        response.setContentType("text/plain;charset=utf-8");        PrintWriter out = response.getWriter();        out.println(this.a + this.b);        out.flush();    } catch (Exception e) {    }}

在struts.xml中配置action

    <action name="sum" class="test.AjaxController" method="sum">    </action>

test.jsp再添加一个按钮,并绑定点击事件:

<input type="button" value="Sum" class="buttonsum">

事件

    $('.buttonsum').click(function(){        $.ajax({            type:'GET',            data:{a:1, b:2},            url:'${pageContext.request.contextPath}/sum.action',            success: function(response){                $('.result').html(response);            }        })    })

点击后,会显示a+b的值:
结果

返回一个对象

新建一个名为Product的类:

package test;public class Product {    private String id;    private String name;    private double price;    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public double getPrice() {        return price;    }    public void setPrice(double price) {        this.price = price;    }    public Product(String id, String name, double price) {        super();        this.id = id;        this.name = name;        this.price = price;    }    public Product() {        super();    }}

AjaxController中添加一名为jsonData的HashMap,添加一个find方法

private Map<String, Object> jsonData = new HashMap<String, Object>();public Map<String, Object> getJsonData() {    return jsonData;}public void setJsonData(Map<String, Object> jsonData) {    this.jsonData = jsonData;}public String find(){    jsonData.put("product", new Product("p1", "Name 1", 1000.00));    return SUCCESS;}

struts.xml中配置此action

<package name="json" namespace="/" extends="json-default">    <action name="find" class="test.AjaxController" method="find">        <result type="json">            <param name="root">jsonData</param>        </result>    </action></package>

test.jsp中新增一个find按钮,并添加事件

<input type="button" value="Find" class="buttonfind">

事件

    $('.buttonfind').click(function(){        $.ajax({            type: "GET",            headers: {                Accept: "application/json; charset=utf-8",                "Content-type" : "application/json; charset=utf-8"            },            url:'${pageContext.request.contextPath}/find.action',            success: function(response){                var result = 'Id: ' + response.product.id + '<br>Name: ' +response.product.name+'<br>price: '+response.product.price;                $('.result').html(result);            }        })    })

结果如下:

结果如下

返回一组对象

AjaxController中新建一个findAll() 方法

public String findAll(){    List<Product> listProduct = new ArrayList<Product>();    listProduct.add(new Product("p1", "Name 1", 1000.00));    listProduct.add(new Product("p2", "Name 1", 2000.00));    listProduct.add(new Product("p3", "Name 3", 3000.00));    jsonData.put("lp", listProduct);    return SUCCESS;}

在struts.xml中配置action

    <action name="findall" class="test.AjaxController" method="findAll">        <result type="json">            <param name="root">jsonData</param>        </result>    </action>

test.jsp中添加一个Find All按钮,并添加事件

    $('.buttonfindall').click(function(){        $.ajax({            type: "GET",            headers: {                Accept: "application/json; charset=utf-8",                "Content-type" : "application/json; charset=utf-8"            },            url:'${pageContext.request.contextPath}/findall.action',            success: function(response){                var n = response.lp.length;                var result = '';                for(var i=0; i<n; i++){                    result += '<br>Id: '+response.lp[i].id+' Name: '+response.lp[i].name+' Price: '+response.lp[i].price+'<br>';                }                $('.result').html(result);            }        })    })

点击后结果如下:
结果

参考文档

  • Struts2返回JSON对象的方法总结
0 0
原创粉丝点击