前段时间对Struts2和json数据的交互有些问题,虽然Struts2的确是有点旧,但是因为项目的原因,还是决定记录一下,以免忘记。
这里主要是记录从后台传到前段的问题
一般分为两种方法:
Struts.xml
1.
<action name="getJson" class="TestClass" method="getJson"></action>
public void getJson(){
HttpServletResponse response = ServletActionContext.getResponse();
Student student= new Student("23","Mary");
JsonObject json = JsonObject.fromObject(student);
PrintWriter out = response.getWriter();
out.write(json);
out.close();
}
这样就可以直接将数据传到前端
2.
<action name="getJson" class="TestClass" method="getJson">
<result type="json" name="success">
<param root>student</param>
</result>
</action>
如果<result>标签中没有嵌套<param>,Struts2会将Action中的属性都封装成json数据
struts.xml 需要继承json-default
private Student student;
public Student getStudent(){return student;}
public void setStudent(Student student){ this.student = student;}
public void getJson(){
student= new Student("23","Mary");
return SUCCESS;
}