java后台设计简单的json数据接口,设置可跨域访问,前端ajax获取json数据

在开发的过程中,有时候我们需要设计一个数据接口。有时候呢,数据接口和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. 
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * 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 li = new ArrayList(); li.add(new kapian("1.jpg","陈永康","2345323","牛逼","10234323","200%","周")); li.add(new kapian("1.jpg","唐露露","123143","稳健","1234234","190%","周")); li.add(new kapian("1.jpg","宋豪杰","2345323","牛逼","10234323","200%","周")); li.add(new kapian("1.jpg","小斌","2345323","牛逼","10234323","200%","周")); li.add(new kapian("1.jpg","李研","2345323","厉害","234235","2000%","周")); li.add(new kapian("1.jpg","陈永康","2345323","牛逼","10234323","200%","月")); li.add(new kapian("1.jpg","唐露露","123143","稳健","1234234","190%","月")); li.add(new kapian("1.jpg","宋豪杰","2345323","牛逼","10234323","200%","月")); li.add(new kapian("1.jpg","小斌","2345323","牛逼","10234323","200%","月")); li.add(new kapian("1.jpg","李研","2345323","厉害","234235","2000%","月")); li.add(new kapian("1.jpg","陈永康","2345323","牛逼","10234323","200%","年")); li.add(new kapian("1.jpg","唐露露","123143","稳健","1234234","190%","年")); li.add(new kapian("1.jpg","宋豪杰","2345323","牛逼","10234323","200%","年")); li.add(new kapian("1.jpg","小斌","2345323","牛逼","10234323","200%","年")); li.add(new kapian("1.jpg","李研","2345323","厉害","234235","2000%","年")); li.add(new kapian("1.jpg","陈永康","2345323","牛逼","10234323","200%","总")); li.add(new kapian("1.jpg","唐露露","123143","稳健","1234234","190%","总")); li.add(new kapian("1.jpg","宋豪杰","2345323","牛逼","10234323","200%","总")); li.add(new kapian("1.jpg","小斌","2345323","牛逼","10234323","200%","总")); li.add(new kapian("1.jpg","李研","2345323","厉害","234235","2000%","总")); try{ JSONArray json = new JSONArray(); for(kapian a :li){ JSONObject obj = new JSONObject(); obj.put("imgurl",a.getImgurl()); obj.put("name",a.getName()); obj.put("money",a.getMoney()); obj.put("style",a.getStyle()); obj.put("num",a.getNum()); obj.put("revenue",a.getRevenue()); obj.put("id",a.getId()); json.put(obj); } JSONObject js =new JSONObject(); response.getWriter().print(json.toString()); } catch(Exception e){ e.printStackTrace(); } } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @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 doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(" A Servlet"); out.println(" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" "); out.println(""); out.flush(); out.close(); } /** * Initialization of the servlet.
* * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }

使用Json的时候,我们要导入JSON包,org.json包,可以网上下载

然后用将设计好的List转换成json格式

我们用到两个json对象,一个是JSONObject,一个是JSONArray。顾名思义,前者就是一个json对象,后者是一个json数组。

这里扩展一下:

最后我们用response.getWrite()和print(),返回数据。也可以用response.getOututStream.write()

write和print的区别

write():仅支持输出字符类型数据,字符、字符数组、字符串等
   print():可以将各种类型(包括Object)的数据通过默认编码转换成bytes字节形式,这些字节都通过write(int c)方法被输出

response.getWriter()和response.getOutputStream的区别:前者是字符流,后者是字节流

response.getOutputStream().write(data.getBytes("UTF-8"));

response.getWriter().write(data);


回到正题:

java后台设计简单的json数据接口,设置可跨域访问,前端ajax获取json数据_第1张图片


这是项目的文件接口,然后浏览器中输入

http://192.168.3.60:8089/Data/servlet/message

java后台设计简单的json数据接口,设置可跨域访问,前端ajax获取json数据_第2张图片


现在如果我们在另外一台电脑上使用ajax, 来获取数据

  $.ajax({
    	url:'http://localhost:8089/Data/servlet/message',
    	method:'get',
      dataType:'json',
    	success:function(data){

       
        $.each(data,function(i,term){

    		alert(term.name);
    		});
    	},
    	error:function(XMLHttpRequest,textStatus,errorThrown){

    		alert(XMLHttpRequest.status);
    		alert(XMLHttpRequest.readyState);
    		alert(textStatus);

    	}

    });

这个时候回到error的回调函数,XMLHtppRequset.status=0;readyState=0; 都是0。 0表示请求根本没有建立。这是因为,另一个电脑和我的数据接口

不在一个服务器上,当然,如果你在自己的电脑上写ajax也不可以,必须写到项目里,才可以访问。所以,跨域问题必须要解决。网上的办法很简单,

新建一个Filter类:

Filter是一个过滤器。对你设定的请求地址进行拦截,然后设置。

package Filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;


public class HeaderFilter implements Filter 
{ 
	public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException
 	{
	HttpServletResponse response = (HttpServletResponse) resp; response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错 
	response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); 
	response.setHeader("Access-Control-Max-Age", "3600"); //设置过期时间 
	response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization"); 
	response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1. 
	response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0"); 
	chain.doFilter(request, resp); 
	} 
	public void init(FilterConfig filterConfig) {} 
	public void destroy() {}
}

在web.xml中配置:

 
      HeaderFilter
      Filter.HeaderFilter
    
    
      HeaderFilter
      /*
    


然后,ajax在任何地方就都可以访问了。


还有一点就是,ajax在处理json数据的时候:

有两种方式,一种数据格式不声明为json,直接是文本,然后传过来,需要解析一下,用eval() 或者JSON.parse()

还有一种,是声明为json,直接可以用

后端和前端,如果有一个声明为json,那么格式就是json.


你可能感兴趣的:(Web开发技术)