日期:2014-05-16 浏览次数:20342 次
最近在做struts+ajax+json项目,项目中使用了struts2-json-plugin-2.2.3.jar(一款json转化插件),研究了一段时间,今天来总结一下具体的使用过程。
使用struts2-json-plugin-2.2.3.jar需要理解以下几点:1、struts2-json-plugin-2.2.3.jar就是一个将对象属性转化成json的东东,2、要转化的对象中必须要有get打头的函数才可以(所以,如果使用struts2-json-plugin-2.2.3.jar,尽量避免在要转化的对象中将不想转化json的的函数使用get*打头),不多说了,下面看配置:
1、我的程序目录结构,由于这是一个struts插件,所以必须要有struts才可以。
2、我的java文件:
StudentEntity.java
import java.io.Serializable; public class StudentEntity implements Serializable { private String stuName; private String stuAge; private String stuSex; public String getStuAge() { return stuAge; } public void setStuAge(String stuAge) { this.stuAge = stuAge; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public String getStuSex() { return stuSex; } public void setStuSex(String stuSex) { this.stuSex = stuSex; } }
TeacherEntity.java
import java.io.Serializable; public class TeacherEntity implements Serializable { private String teacName; private String teacAge; private String teacSex; public String getTeacAge() { return teacAge; } public void setTeacAge(String teacAge) { this.teacAge = teacAge; } public String getTeacName() { return teacName; } public void setTeacName(String teacName) { this.teacName = teacName; } public String getTeacSex() { return teacSex; } public void setTeacSex(String teacSex) { this.teacSex = teacSex; } }
StrIndex.java(这是一个action,命名不规范)
import java.util.Date; import org.apache.struts2.json.annotations.JSON; import com.opensymphony.xwork2.ActionSupport; public class StrIndex extends ActionSupport { private TeacherEntity teacher=new TeacherEntity(); private StudentEntity student=new StudentEntity(); private Date nowd=new Date(); public String toIndex(){ teacher.setTeacName("张三"); teacher.setTeacAge("100"); teacher.setTeacSex("男男"); student.setStuName("李老师"); return SUCCESS; } // 是否转换该对象 // @JSON(serialize=true) // @JSON(name="newName") public StudentEntity getStudent() { return student; } public void setStudent(StudentEntity student) { this.student = student; } public TeacherEntity getTeacher() { return teacher; } public void setTeacher(TeacherEntity teacher) { this.teacher = teacher; } @JSON(format="yyyy-MM-dd") public Date getNowd() { return nowd; } public void setNowd(Date nowd) { this.nowd = nowd; } }
紧接着是我的struts配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="test-default" extends="json-default"> <action name="ind" class="StrIndex" method="toIndex"> <result name="success" type="json"> </result> </action> </package> </struts>
3、简单配置说明
在struts中使用struts2-json-plugin-2.2.3.jar需要将要返回json的action配置在
<package name="test-default" extends="json-default"> ... ... </package>
中,注意extends="json-default"继承的是“json-default" 我们正常配置struts是使用‘struts-default’,所以需要将返