如何在struts2中仅获取特定字段作为响应

2022-01-16 00:00:00 regex json jquery java struts2

我有一个动作类,其中定义了许多动作方法,并且还定义了适当的 getter 和 setter 方法.我有一些操作方法,我通过从 jQuery 调用它们来获取 json 格式的数据.但是当我获得 json 数据时,它包括定义了 getter 和 setter 的所有字段,但我只想获取由我正在调用的方法填充的字段.例如-

I have an action class in which many action methods are defined and appropriate getters and setters methods are also defined. I have some action methods from which I get the data as json by calling them from jQuery. but when I get the json data it includes all the fields for which getters and setters are defined but i want to get only that field which is filled by that method to which i am calling. for example-

public class ApplicantRegistration extends ActionSupport{
private String s1;
private XyzBean bean;
private String s2;
// respective getters and setters....

public String m1(){
// some work
 return SUCCESS;
}

public String m2(){
   //some work
    s2="abc";
    return SUCCESS;
}


}

当我通过 jQuery 调用方法 m2 并获得 json 响应时,它给出了

when i call method m2 via jQuery and get json response it gives

{
 s1: null,
 bean: null,
 s2:"abc",
 m2: "success",

}

但我只想要

{
 s2:"abc"
}

推荐答案

默认 json result 序列化 root 参数指定的所有 bean 属性,默认设置为那个行动.但是您可以使用结果的 includeProperties 参数来仅过滤 root 中与正则表达式匹配的那些属性.

By default json result serializes all bean properties specified by the root parameter which is set by default to the action. But you can use includeProperties parameter of the result to filter only those properties from the root that matched regex expressions.

@Result(type="json", params = {"includeProperties", "^s2"})

相关文章