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.
java后台设计简单的json数据接口,设置可跨域访问,前端ajax获取json数据的更多相关文章
- spring boot + spring security +前后端分离【跨域】配置 + ajax的json传输数据
1.前言 网上各个社区的博客参差不齐 ,给初学者很大的困扰 , 我琢磨了一天一夜,到各个社区找资料,然后不断测试,遇到各种坑,一言难尽啊,要么源码只有一部分,要么直接报错... 最后实在不行,直接去看 ...
- qt qml ajax 获取 json 天气数据示例
依赖ajax.js类库,以下代码很简单的实现了获取天气json数据并展示的任务 [TestAjax.qml] import QtQuick 2.0 import "ajax.js" ...
- jQuery中使用Ajax获取JSON格式数据示例代码
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式.JSONM文件中包含了关于“名称”和“值”的信息.有时候我们需要读取JSON格式的数据文件,在jQuery中 ...
- Jquery 模板插件 jquery.tmpl.js 的使用方法(1):基本语法,绑定,each循环,ajax获取json数据
jquery.tmpl.js 是一个模板js ,主要有2个方法 (1):$.template()方法,将一段script或者是Html编译为模板,例如 $.template('myTemplate' ...
- 通过Jquery中Ajax获取json文件数据
1. JSON(JavaScript Object Notation): javaScript对象表示法: 是存储和交换文本信息的语法,比xml更小,更快,更易解析. 2. JSON基本书写格式 : ...
- ajax获取json数据及实现跨域请求
最近想练习一下ajax获取json数据 , 首先上网找一些在线的可用来测试的接口. -----------------------------------------------------这里是接口 ...
- 使用Cors后台设置WebAPI接口跨域访问
昨天根据项目组前端开发工程师反映,在浏览器端无法直接使用ajax访问后台接口获取数据,根据他的反映,我查阅了相关跨域的解决方案: 一:使用jsonP,但是jsonP只能使用GET请求,完全不符合我项目 ...
- Ajax获取 Json文件提取数据
摘自 Ajax获取 Json文件提取数据 1. json文件内容(item.json) [ { "name":"张国立", "sex":&q ...
- JS-利用ajax获取json数据,并传入页面生成动态tab
封装好的:ajax.js function ajax(url, fnSucc,fnFaild){ //1[创建] if(window.XMLHttpRequest){ var oAjax = new ...
随机推荐
- linux如何通过脚本来修改用户的密码?脚本自动化修改用户密码?
需求描述: linux环境中在创建用户的时候,涉及到修改用户的密码,一般是通过passwd命令进行修改,需要多次的确认,这里考虑通过一条命令直接对密码进行修改 不需要进行交互的方式.在此记录. 操作过 ...
- Log4net用法(App.config配置)
配置文件 <configSections> <section name="log4net" type="log4net.Config.Log4NetCo ...
- 使用dshow捕获摄像头图像
#include "stdafx.h" #include <DShow.h> #include <Guiddef.h> #include <strmi ...
- Nginx(十一)-- keepalived简介
1. 什么是keepalived 基于VRRP(虚拟路由器冗余协议)来实现对web服务的高可用方案. keepalived下载地址:http://download.csdn.net/detail/u0 ...
- C#调用DLL报“试图加载格式不正确的程序”
项目右键属性->项目设计器->生成->平台->把'默认设置(任何 CPU)'改为x86或者x64
- N76E003之WDT(看门狗定时器)
N76E003提供一个看门狗定时器(WDT),它可以配置成一个超时复位定时器用于复位整个设备.一旦由于外界干扰设备进入非正常状态或挂起,看门狗可以复位恢复系统.这有用于监测系统运行以提高系统可靠性.对 ...
- spring boot配置文件application.propertis
转自http://www.qiyadeng.com/post/spring-boot-application-properties 本文记录Spring Boot application.proper ...
- Android学习之AutoCompleteTextView
AutoCompleteTextView有点类似于EditText和Spinner的混合体.当用户在输入时,如果应用程序的文本输入框中使用了自动完成控件,预输入文本被看作是一个前缀过滤器,与用户当前输 ...
- uefi安装win7,deepin15双系统后grub没有windows选项
本帖最后由 873792861 于 2015-12-23 16:17 编辑 如题,首先电脑是GPT+uefi的,电脑上安装有64位的win7.用U盘工具制造好驱动U盘后,在安装时选择 专家模式 ,选择 ...
- CSS-筛选 获取第一个td
tr td:first-child{ font-weight:bold; } 看样子,应该是jquery中有些筛选,css也是能够同样进行筛选的,只是模式有些可能不同 a[data-toggle*=' ...