我在Extjs4.1中创建了一个简单的表单。
我正在将请求发送到 Struts2 框架,并使用 Strtus2JSON 插件,我必须收到响应。但不幸的是,响应为空。
Action 类
public String execute()throws Exception{
Employee emp = new Employee();
emp.setAddress(getAddress());
emp.setDepartment(getDepartment());
emp.setName(getName());
emp.setSalary(getSalary());
AddEmployeeService empService = new AddEmployeeService();
boolean flag = empService.addEmployee(emp);
resultJSONobj = new JSONObject();
if(flag == true)
resultJSONobj.put("success","Inserted Successfully");
else
resultJSONobj.put("failure","An error occured");
System.out.println(resultJSONobj);
return SUCCESS;
}
struts.xml
<struts>
<package name="default" extends="struts-default, json-default">
<action name="AddEmp" class = "actions.AddEmpAction">
<result name = "success" type="json">
<param name ="root">resultJSONobj</param>
</result>
</action>
</package>
</struts>
有人能告诉我为什么我得到的响应为空吗?
最佳答案
你有像这样的 resultJSONobj 的 Getter 吗?:
public JSONObject getResultJSONobj(){
return this.resultJSONobj;
}
向您的包添加命名空间,如下所示:
<package name="default" namespace="/" extends="struts-default, json-default">
看看是否有什么改变......
<小时/>编辑
- 'transient' fields are not serialized
- fields without getter method are not serialized
尝试这样:
使用 Map 而不是 JSONObject。并非每个类都被接受,并且我不确定您的 JSONObject 是否可序列化(您是否实现可序列化?您是否声明了serialVersionUID?等等)
private Map resultJSONobj = new HashMap(); //instantiated at class level
// accessors
public Map getResultJSONobj() {
return resultJSONobj;
}
public void setResultJSONobj(Map resultJSONobj) {
this.resultJSONobj = resultJSONobj;
}
//...
public String execute()throws Exception{
Employee emp = new Employee();
emp.setAddress(getAddress());
emp.setDepartment(getDepartment());
emp.setName(getName());
emp.setSalary(getSalary());
AddEmployeeService empService = new AddEmployeeService();
boolean flag = empService.addEmployee(emp);
if(flag == true)
resultJSONobj.put("success","Inserted Successfully");
else
resultJSONobj.put("failure","An error occured");
System.out.println(resultJSONobj);
return SUCCESS;
}
并像这样更改 struts 配置:
<struts>
<package name="default" extends="struts-default, json-default">
<action name="AddEmp" class = "actions.AddEmpAction">
<result name="success" type="json" />
</action>
</package>
</struts>
成功不是必需的,但为了更清晰的代码而保留它,以后您可以随时将其删除。
现在,您应该看到这样的结果(如果您没有任何其他 getter):
{
"resultJSONobj": {
"success":"Inserted Successfully"
}
}
或
{
"resultJSONobj": {
"failure":"An error occured"
}
}
关于java - JSON 和 Struts2 结果为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915089/