Hitesh Hitesh - 1 month ago 12
Ajax Question

How to exclude param from response in struts 2 and send the object we want?

I want JSON result for Ajax request, but my requirement is to send only the

ArrayList
of object and exclude some of the parameter present in action class. So how to do this?

This is my action class

public class AjaxAction{
private int color;
private String prodId;
private List<Product> productList;


public String execute(){
productList= service.getProductList();//this method is getting list of products
HttpServletResponse response = ServletActionContext.getResponse();

Gson gson = new Gson();
JsonElement element = gson.toJsonTree(productList,
new TypeToken<List<Product>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
try {
response.getWriter().print(jsonArray);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}


And my
struts.xml
file is:

<package name="json" namespace="/" extends="json-default">
<interceptors>
<interceptor-stack name="mystack">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="getProduct" class="com.xyz.action.AjaxAction">
<result name="success" type="json" />
<param name="root">productList</param>
</action>
</package>


So when i check my console data returned from action is having other variable in it. How to avoid that?

Answer

You can return stream result

<action name="getProduct" class="com.xyz.action.AjaxAction">
    <result name="success" type="stream">
      <param name="contentType">application/json</param>
    </result>
</action>

and in the action

private InputStream inputStream;

//getter here
public InputStream getInputStream () {
  return inputStream;
}


public String execute(){
  productList= service.getProductList();//this method is getting list of products

  Gson gson = new Gson();
  JsonElement element = gson.toJsonTree(productList,
        new TypeToken<List<Product>>() {
        }.getType());
  JsonArray jsonArray = element.getAsJsonArray();
  inputStream = new ByteArrayInputStream(jsonArray.toString().getBytes());
  return "success";
}