项目开发中,很多时候需要使用ajax+json来获取服务器数据, 同时服务器也会采用返回json数据以达到跨平台访问的形式:
我们利用sturts2 完成一个demo,自行搭建struts2的环境:
1、实体类:
import java.util.Date;
public class Role {
private int id;
private String name;
private String createDate;
public Role(){}
public Role(int id, String name, String createDate) {
super();
this.id = id;
this.name = name;
this.createDate = createDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
}
2、struts2 action实现
package com.xingxue.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.xingxue.model.Role;
public class RoleAction {
public String getData() {
HttpServletResponse response = ServletActionContext.getResponse();
try {
PrintWriter out = response.getWriter();
Role role = new Role(1,"财务",new Date().toString());
JSONObject jsonStr = JSONObject.fromObject(role);
String str = jsonStr.toString();
out.print(str);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
3、js获取数据实现:
package com.xingxue.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import com.xingxue.model.Role;
public class RoleAction {
public String getData() {
HttpServletResponse response = ServletActionContext.getResponse();
try {
PrintWriter out = response.getWriter();
Role role = new Role(1,"财务",new Date().toString());
JSONObject jsonStr = JSONObject.fromObject(role);
String str = jsonStr.toString();
out.print(str);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}