Next, we will see the core of the post.We are going to create the custom result which sends JSON data string back to the client. The only requirement needs to create a struts2 custom result is, implementing
interface of struts 2. Here is the source code to create a custom result type and serialize the object in to JSON.
package com.axiohelix.pda.jsonresult;
import java.io.PrintWriter;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.ValueStack;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
public class JSONResult implements Result{
private static final long serialVersionUID = 1L;
public static final String DEFAULT_PARAM = "classAlias";
String classAlias;
public String getClassAlias() {
return classAlias;
}
public void setClassAlias(String classAlias) {
this.classAlias = classAlias;
}
@Override
public void execute(ActionInvocation invocation) throws Exception {
ServletActionContext.getResponse().setContentType("text/plain");
ServletActionContext.getResponse().addHeader("Cache-Control", "no-cache");
PrintWriter responseStream = ServletActionContext.getResponse().getWriter();
ValueStack valueStack = invocation.getStack();
Object jsonModel = valueStack.findValue("jsonModel");
XStream xstream = new XStream(new JettisonMappedXmlDriver());
if ( classAlias == null ){
classAlias = "object";
}
xstream.alias(classAlias, jsonModel.getClass() );
responseStream.println(xstream.toXML( jsonModel ));
}
}
Here, I have used two open source libraries,
XStream and
Jettison. XStream helps to serialize java objects into XML format while Jettison helps to create JSON from the XML.As you can see,I am getting "jsonModel" property exposed into the
ValueStack from our
ViewUsers action calss,progrmmetically and serialize it into JSON.
Now the time to tell
ViewUsers action class about our custom result type. We have to add fallowing entries into our declarative architecture, ie
struts.xml file. To declare our custom result type, you have to add fallowing into
struts.xml file.
<result-types>
<result-type name="customJSON" class="com.axiohelix.pda.jsonresult.JSONResult">
</result-type>
</result-types>
To use our custom result type, we need to add the fallowing to
struts.xml file.
<action name="ViewUsers" class="com.axiohelix.pda.actions.ViewUsers">
<result type="customJSON">user</result>
</action>
Here, you can see, I am passing in a parameter to the custom result type. It will be set to the "classAlias" field and finally, it will be the name of the root JSON object return to the client. Fallowing is the response JSON string representation of JSON
{"user":{"username":"Mary",
"password":"max",
"age":"28",
"firstName":"Mary",
"lastName":"Greene",
"receiveJunkMail":"false"}}