如何将Struts2动作类中的InputStream值传递给jsp页面中的ajax并将其转换为Json Array [英] How to pass InputStream value in Struts2 action class to ajax in jsp page and convert the value into Json Array

查看:88
本文介绍了如何将Struts2动作类中的InputStream值传递给jsp页面中的ajax并将其转换为Json Array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Struts2动作类的json数组传递给jsp页面.我正在尝试将数据集作为字符串发送.我想知道的是,如何在javascript中读取这些数据.

I want to pass json array from Struts2 action class to jsp page. I'm trying to send the data set as a string. The thing I want to know is, How can I read those data in javascript.

这是我在动作类中的方法

This is my method in action class

private InputStream inputStream;

/* getter and setter*/

public String getClientMilestone() throws DAOTransientException, DBConfigException{
        PaymentScheduleDao paymentScheduleDao = new PaymentScheduleDao();
        List <PaymentMilestone> paymentScheduleInfo = paymentScheduleDao.getClientMilestoneInfo(projectId);
        String result = "[";

        for(int i=0; i<paymentScheduleInfo.size(); i++){

            result += "{"+"'"+"item"+i+"' : {"+ "'"+"milestoneName"+ "'"+":"+"'"+paymentScheduleInfo.get(i).getMilestone_name()+"'"+"}"+"},";

        }
        result += "]";
        System.out.println("result is "+result);
        inputStream = new StringBufferInputStream(result);
        return "success";
    }

它打印如下

result is [{'item0' : {'milestoneName':'milestone 1'}},{'item1' : {'milestoneName':'milestone 2'}}]

struts.xml

struts.xml

<package name="ClientMilestone" namespace="/" extends="struts-default">
        <action name="getClientMilestone" class="packageName.PaymentScheduleAction" method="getClientMilestone">
            <result name="success" type="stream">
            <param name="contentType">text/html</param>
            <param name="inputName">inputStream</param>
            </result>
            <result name="failure">./LandingPage.jsp</result>
            <result name="error">./Error.jsp</result>
        </action>
    </package>

jsp中的javascript函数

javascript function in jsp

function createOrViewPs() {

    var projectId = document.getElementById("projectId").value;
    $.ajax({ 
        method: "GET",
        url: "getClientMilestone",
        data: {"projectId" : projectId},
        traditional: true, 
        success:
            function(result){
                var jsonArr = result;

                for (var i=0; i<jsonArr.length; i++)
                    for (var name in jsonArr[i]) {
                        alert("Item name: "+name);
                        alert("Source: "+jsonArr[i][name].milestoneName);
                }
            },
        error: 
            function(){
                alert("fail");
            }
    });         
} 

推荐答案

因为您从服务器返回了带有stream结果类型的JSON字符串化版本(请注意,流结果类型可能不合适,请参见下文) ,则需要使用 JSON.parse将其解析为JSON (),如果您使用的是jQuery,则最好使用 $ .each

Because you return a stringified version of JSON from the server with the stream result type (Note, that stream result type might not be appropriate, see below), you need to parse it to JSON with JSON.parse() and if you are using jQuery better use $.each

var jsonArr = JSON.parse(result);
$.each (jsonArr, function(index, value){
  $.each (value, function(key, value){
    console.log("Item name: "+key);
    console.log("Source: "+value.milestoneName);
  });
});


您做错了什么是手动构建json.您应该使用将Java对象序列化为JSON的工具. Struts2在软件包中具有 json-lib 可用的jar,可用于序列化为json,或者您使用的是 struts2-json-plugin ,则它具有内置的序列化程序.如果您使用的是 struts2-rest-plugin ,则可以使用杰克逊.您选择用于序列​​化数据的库的方式超出了此答案的范围.您可以在SO和 Struts网站上找到许多示例.其中大多数使用JSON插件返回浏览器支持的JSON对象,即不需要解析,但是对JSON进行解析有助于避免错误和数据丢失.


What you did wrong is building json manually. You should use a tool that serializes Java object to JSON. Struts2 has json-lib available jar in the package that can be used to serialize to json, or if you are using struts2-json-plugin then it has built-in serializer. if you are using struts2-rest-plugin then you can use other serializer like Jackson. The way you choose the library to serialize your data is out of the scope of this answer. You can find many examples on SO and on Struts site. Most of them using json plugin that returns JSON object that supports by the browser, i.e. doesn't need parsing, however parsing for JSON is useful to avoid errors and data lose.

这篇关于如何将Struts2动作类中的InputStream值传递给jsp页面中的ajax并将其转换为Json Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆