1

I have this problem: I need to get some simple data from Action and send back to JSP (already loaded), so I have to manage the action to recover that data with jQuery $.ajax method. So here is my code:

MyAction.java

private String employee;
private InputStream inputStreamEmployee;
//these with getter/setter

public String someData() throws Exception{
        employee= "John Doe";
        inputStreamEmployee = new ByteArrayInputStream(
                  employee.getBytes(StandardCharsets.UTF_8)); 

        return "SUCCESS";
    }

struts.xml

<action name="getSomeData" method="someData" class="MyAction">
    <result name="success" type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">inputStreamEmployee</param>
    </result>
</action>

data.js

function getData(){
    $.ajax({
        type: 'GET',
        url: 'getSomeData',
        dataType: 'text',
        async: true,
        success: function (data) {
            alert(data);
        },
        error: function (data) {
            alert('no data!!');
        }
    });

I checked this resource, but I need the javascript part. So I debugged and checked the development. The javascript method calls the action in java, and action returns success, but the data in function(data) doesn't get the InputStream correctly, it just get the whole html webpage source, as shown in the image: enter image description here

What am I doing wrong? Thanks in advance.

mindOf_L
  • 911
  • 2
  • 13
  • 23
  • Also I tried with some questions here, like http://stackoverflow.com/questions/17093862/issue-returning-json-value and, http://stackoverflow.com/questions/28221528/return-a-string-from-struts2-action-to-jquery, but with no solutions. – mindOf_L Jan 26 '17 at 12:03
  • What's the content of the HTML? Why are you setting the contentType to HTML if you don't want to return HTML? Why not use the JSON plugin? – Dave Newton Jan 26 '17 at 13:05
  • The results are explicitly mapped via annotations but you have probably wrong action mapping. – Roman C Jan 26 '17 at 14:07

1 Answers1

1

Forget the javascript calls, your problem is that the request www.yourdomain.com/getSomeData is not returning a page with the text John Doe.

Why are you using an inputStream? If you are using JSP as templating system a simple solution would be

MyAction.java

private String employee;

public String someData() throws Exception{
    employee= "John Doe";
    return "SUCCESS";
}


public String getEmployee(){
    return employee;
}

stuts.xml

<action name="getSomeData" method="someData" class="MyAction">
    <result>/WEB-INF/.../templates/some_data.jsp</result>
</action>

some_data.jsp

<%= employee%>
fustaki
  • 1,574
  • 1
  • 13
  • 20