简体   繁体   English

如何将 Struts 2 动作类中的 InputStream 值传递给 JSP 页面中的 Ajax 并将该值转换为 JSON 数组

[英]How to pass InputStream value in Struts 2 action class to Ajax in JSP page and convert the value into JSON Array

I want to pass JSON array from Struts 2 action class to JSP page.我想将 JSON 数组从 Struts 2 动作类传递到 JSP 页面。 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.我想知道的是,如何在 JavaScript 中读取这些数据。

This is my method in Action class:这是我在Action类中的方法:

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";
    }

It prints as below:它打印如下:

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>

JavaScript function in JSP: JSP中的JavaScript函数:

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");
            }
    });         
} 

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因为您使用stream结果类型从服务器返回 JSON 的字符串化版本(注意,该流结果类型可能不合适,见下文),您需要使用JSON.parse()将其解析为 JSON,如果您正在使用jQuery 更好地使用$.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);
  });
});

What you did wrong is building json manually.您做错的是手动构建 json 。 You should use a tool that serializes Java object to JSON.您应该使用将 Java 对象序列化为 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. Struts2 的包中有json-lib可用的 jar,可用于序列化为 json,或者如果您使用的是struts2-json-plugin ,则它具有内置的序列化程序。 if you are using struts2-rest-plugin then you can use other serializer like Jackson .如果您使用的是struts2-rest-plugin那么您可以使用其他序列化程序,如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 .您可以在 SO 和Struts 网站上找到许多示例。 Most of them using json plugin that returns JSON object that supports by the browser, ie doesn't need parsing, however parsing for JSON is useful to avoid errors and data lose.他们中的大多数使用返回浏览器支持的JSON对象的json插件,即不需要解析,但是解析JSON对于避免错误和数据丢失很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM