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. <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.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. <br>
	 *
	 * 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the POST method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @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);

回到正题:

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

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

现在如果我们在另外一台电脑上使用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中配置:

 <filter>
      <filter-name>HeaderFilter</filter-name>
      <filter-class>Filter.HeaderFilter</filter-class><!--你过滤器的包 -->
    </filter>
    <filter-mapping>
      <filter-name>HeaderFilter</filter-name>
      <url-pattern>/*</url-pattern><!-- 你开放的接口前缀  -->
    </filter-mapping>

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

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

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

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

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Jaycekon

深入浅出Redis-Spring整合Redis

概述:    在之前的博客中,有提到过Redis 在服务端的一些相关知识,今天主要讲一下Java 整合Redis的相关内容。    下面是Jedis 的相关依赖...

3619
来自专栏pangguoming

Java 解析Excel文件为JSON

Excel转Json的需求 反正我对SSM基本不会的情况下来到现在这家公司,都是90后,感觉很好。第二天就给我开发任务,就是把用户上传的Excel文件转成JSO...

5755
来自专栏编码小白

tomcat请求处理分析(六)servlet的处理过程

1.1.1.1  servlet的解析过程 servlet的解析分为两步实现,第一个是匹配到对应的Wrapper,第二个是加载对应的servlet并进行数据,这...

7107
来自专栏Java技术分享

Servlet是如何实现MVC的?

Servlet是一种服务器端的编程语言,是J2EE中比较关键的组成部分,Servlet技术的推出,扩展了Java语言在服务器端开发的功能,巩固了Java语言在服...

2528
来自专栏大前端_Web

easyUI组件datagrid的二次封装

版权声明:本文为吴孔云博客原创文章,转载请注明出处并带上链接,谢谢。 https://blog.csdn.net/wkyseo/articl...

2633
来自专栏刘望舒

LeakCanary看这一篇文章就够了

LeakCanary是Square公司基于MAT开源的一个内存泄漏检测工具,在发生内存泄漏的时候LeakCanary会自动显示泄漏信息。

1.9K5
来自专栏xingoo, 一个梦想做发明家的程序员

文件上传之Apache commons fileupload使用

  文件上传的方法主要目前有两个常用的,一个是SmartUpload,一个是Apache的Commons fileupload.   我们这里主要介绍下第二个的...

2569
来自专栏大内老A

通过一个模拟程序让你明白ASP.NET MVC是如何运行的

ASP.NET MVC的路由系统通过对HTTP请求的解析得到表示Controller、Action和其他相关的数据,并以此为依据激活Controller对象,调...

2916
来自专栏java初学

j2ee—框架(1):Servlet+JSP实现基本的登录功能(v1.0)

4678
来自专栏Flutter入门

Weex是如何在Android客户端上跑起来的

Weex可以通过自己设计的DSL,书写.we文件或者.vue文件来开发界面,整个页面书写分成了3段,template、style、script,借鉴了成熟的MV...

4305

扫码关注云+社区

领取腾讯云代金券