tags:

views:

1485

answers:

2

Hi,

I want to send String as a response to the AJAX xhrPOST method. I am using Struts2 to implement the server side processing. But, I am not getting how to send the result "type" as string and the mapping which should be done to send the string from the struts2 action class to the AJAX response.

+1  A: 

You could create a simple StringResult pretty easily by extending StrutsResultSupport, but nothing exists built-in to the framework as far as I know.

Here's an implementation that I've used in the past of a simple StringResult:

public class StringResult extends StrutsResultSupport {
private static final Log log = LogFactory.getLog(StringResult.class);
private String charset = "utf-8";
private String property;
private String value;
private String contentType = "text/plain";


@Override
protected void doExecute(String finalLocation, ActionInvocation invocation)
  throws Exception {
 if (value == null) {
  value = (String)invocation.getStack().findValue(conditionalParse(property, invocation));
 }
 if (value == null) {
  throw new IllegalArgumentException("No string available in value stack named '" + property + "'");
 }
 if (log.isTraceEnabled()) {
  log.trace("string property '" + property + "'=" + value);
 }
 byte[] b = value.getBytes(charset);

 HttpServletResponse res = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);

 res.setContentType(contentType + "; charset=" + charset);
 res.setContentLength(b.length);
 OutputStream out  = res.getOutputStream();
 try {
  out.write(b);
  out.flush();
 } finally {
  out.close(); 
 }
}


public String getCharset() {
 return charset;
}


public void setCharset(String charset) {
 this.charset = charset;
}


public String getProperty() {
 return property;
}


public void setProperty(String property) {
 this.property = property;
}


public String getValue() {
 return value;
}


public void setValue(String value) {
 this.value = value;
}


public String getContentType() {
 return contentType;
}


public void setContentType(String contentType) {
 this.contentType = contentType;
}

}

I've used the json plugin to do similar things. If you use that, you can use the following to expose a single String property in your action:

<result name="success" type="json">
  <param name="root">propertyToExpose</param>
</result>
Brian Yarger
+1  A: 

You can have your action method return not a String result, but a result of type StreamResult.

In other words:

class MyAction {

 public StreamResult method() {
   return new StreamResult(new ByteArrayOuputStream("mystring".getBytes()));
 }
}

You don't necessarily have to return a String from a Struts2 action method. You can always return an implementation of the Result interface from xwork.

Horia Chiorean
Probably you meant * return new StreamResult(new ByteArrayInputStream("mystring".getBytes())); *This helped, thanks
Aleksey Otrubennikov