在开发的过程中,有时候我们需要设计一个数据接口。有时候呢,数据接口和Web服务器又不在一起,所以就有跨域访问的问题。
第一步:简单的设计一个数据接口。
数据接口,听起来高大上,其实呢就是一个简单的Serlvlet,在有get的请求的时候,返回我们要提供的数据就可以。现在JSON数据格式已经很普遍,因为很方便,所以我们做一个json数据的接口。直接看代码
先建立一个实体类,就是包装我们的数据的
bean/kapian.java
package bean;
public class kapian {
//头像路进
public String imgurl;
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getRevenue() {
return revenue;
}
public void setRevenue(String revenue) {
this.revenue = revenue;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
//名字
public String name;
//金额
public String money;
//交易风格
public String style;
//订阅人数
public String num;
//收益率
public String revenue;
//标记
public String id;
public kapian(String imgurl,String name,String money,String style,String num,String revenue,String id){
this.imgurl=imgurl;
this.name=name;
this.money=money;
this.style=style;
this.num=num;
this.revenue=revenue;
this.id=id;
}
}
Serlvet 类:
bean/message.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.ArrayList;
import bean.kapian;
import java.util.List;
public class message extends HttpServlet {
/**
* Constructor of the object.
*/
public message() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setContentType("text/html;charset=utf-8");
List<kapian> li = new ArrayList<kapian>();
li.add(new kapian("1.jpg","陈永康","2345323","牛逼","10234323","200%","周"));
li.add(new kapian("1.j