我在Extjs4.1中创建了一个简单的表单。
我将请求发送到Struts2框架,并使用Strtus2JSON插件,我必须收到响应。但不幸的是,回复是空的。
动作类
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>
有人可以告诉为什么iam将响应变为null吗?
答案 0 :(得分:1)
你有结果这样的getJSONobj的Getter吗?:
public JSONObject getResultJSONobj(){
return this.resultJSONobj;
}
在包中添加命名空间,如下所示:
<package name="default" namespace="/" extends="struts-default, json-default">
看看是否有变化......
修改强>
- '瞬态'字段未序列化
- 没有getter方法的字段未序列化
试试这样:
使用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>
成功不是必需的,但请留下更清晰的代码,以后可以随时将其删除。
现在,你应该看到这个结果(如果你没有任何其他的吸气剂):
{
"resultJSONobj": {
"success":"Inserted Successfully"
}
}
或
{
"resultJSONobj": {
"failure":"An error occured"
}
}
答案 1 :(得分:1)
在配置文件struts.xml中,请使用
<param name="includeProperties">resultJSONobj.*</param>
而不是
<param name="includeProperties">resultJSONobj</param>
在我的项目之前,我遇到了同样的问题,在我做出上述改变之后,它起作用了。
答案 2 :(得分:0)
struts.xml文件中缺少一些东西。结果成功后,你要去哪里? 在execute方法和inside action类之外创建json对象实例。 Struts2JSON插件序列化动作类中的所有动作变量。可能是因为你只在动作类中声明了JSONobject并且实际在execute中创建它,JSON可能会得到它{}。
把
private JSONObject resultJSONobj = new JSONObject();
在内部动作类和外部执行并查看,它可能会起作用。
有关更多信息,请访问此处
http://struts.apache.org/2.2.3/docs/json-plugin.html