Gsm Gsm - 1 year ago 257
Ajax Question

Return a string from Struts2 action to jQuery

I call a Struts2 action using jQuery Ajax like the following:

$.ajax ({
url: 'callAction.action',
type: 'POST',
data: data,
dataType: 'string',
success: function (data) {

And in response, it has to return a string back to jQuery.

private String result;
//getters and setters

public String call()
//some code
result= "some string";

return SUCCESS;

I want to retrieve the
from the function in the Struts action to jQuery. How would I make this possible?

Answer Source

You can use stream result to get just a String from the action.

Configure your action to use stream result with contentType set to text/plain (or don't use contentType at all, because text/plain is set by default).

<action name="callAction" method="call">
    <result type="stream">
        <param name="contentType">text/plain</param>

In your action create InputStream field with getter/setter and in your action method convert String to the input stream.

private InputStream inputStream;
// getter/setter

public String callAction() {
    inputStream = new ByteArrayInputStream(
            "some string".getBytes(StandardCharsets.UTF_8));
    return SUCCESS;

Then you can execute ajax request like that:

$.ajax ({  
    url: '<s:url action="callAction"/>',
    type: 'POST',
    dataType: 'text',
    success: function (data) {

Note: it is better to use <s:url> tag to construct url-s and there isn't such dataType as string, use text or don't set it at all (jQuery will try to infer it based on the MIME type of the response).