如何在struts 2中从响应中排除参数并发送我们想要的对象?

问题描述 投票:0回答:1

我想要 Ajax 请求的 JSON 结果,但我的要求是仅发送对象的

ArrayList
并排除操作类中存在的一些参数。那么如何做到这一点?

这是我的动作课

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";
}

我的

struts.xml
文件是:

<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>

因此,当我检查从操作返回的控制台数据中是否有其他变量。如何避免这种情况?

java ajax json struts2 gson
1个回答
0
投票

您可以返回

stream
结果

<action name="getProduct" class="com.xyz.action.AjaxAction">
    <result name="success" type="stream">
      <param name="contentType">application/json</param>
    </result>
</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";
}
© www.soinside.com 2019 - 2024. All rights reserved.