首页 > 代码库 > ajax跨域访问数据

ajax跨域访问数据

通过json发送和接受数据,数据以json的格式在服务器端和前台进行传递,什么是json数据?这里就不进行详细阐述,轻自行百度解决。

html5 中利用ajax 异步请求时,会遇到跨域的问题,如果域名不一致、ip地址不一致,端口不一致都会导致跨域请求不成功。

为了解决这个问题,需要在前台和后台均设置相关的属性进行跨域请求。

现在展示服务器端的代码:

自己封装的过滤器:

package utils;
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 CrossDomainFilter implements Filter {
	public void destroy() {
		// TODO Auto-generated method stub
	}
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletResponse res = (HttpServletResponse) resp;
		// 这里最好不要写通配符,如果允许多个域请求数据的话,可以直接用逗号隔开:"http://www.baidu.com,http://google.com"
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
		res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With");
		//res.setHeader("Access-Control-Allow-Credentials","false");
		chain.doFilter(req, resp);
	}
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
	}
}



将字符串转换为json数据格式的工具类:
package utils; 

import java.beans.IntrospectionException;   
import java.beans.Introspector;  
import java.beans.PropertyDescriptor;  
import java.math.BigDecimal;  
import java.math.BigInteger;  
import java.util.List;  
import java.util.Map;  
import java.util.Set;  
import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;

public class JsonUtil {  
private static Log log = LogFactory.getLog(JsonUtil.class); 

public static String object2json(Object obj) {  
             StringBuilder json = new StringBuilder();  
             if (obj == null) {  
               json.append("\"\"");  
             } else if (obj instanceof String || obj instanceof Integer || obj instanceof Float  
                 || obj instanceof Boolean || obj instanceof Short || obj instanceof Double  
                 || obj instanceof Long || obj instanceof BigDecimal || obj instanceof BigInteger  
                 || obj instanceof Byte) {  
               json.append("\"").append(string2json(obj.toString())).append("\"");  
             } else if (obj instanceof Object[]) {  
               json.append(array2json((Object[]) obj));  
             } else if (obj instanceof List) {  
               json.append(list2json((List<?>) obj));  
             } else if (obj instanceof Map) {  
               json.append(map2json((Map<?, ?>) obj));  
             } else if (obj instanceof Set) {  
               json.append(set2json((Set<?>) obj));  
             } else {  
               json.append(bean2json(obj));  
             }  
             return json.toString();  
  }

public static String bean2json(Object bean) {  
             StringBuilder json = new StringBuilder();  
             json.append("{");  
             PropertyDescriptor[] props = null;  
             try {  
               props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();  
             } catch (IntrospectionException e) {}  
             if (props != null) {  
               for (int i = 0; i < props.length; i++) {  
                 try {  
                   String name = object2json(props[i].getName());  
                   String value = http://www.mamicode.com/object2json(props[i].getReadMethod().invoke(bean));  ":");  
                   json.append(value);  
                   json.append(",");  
                 } catch (Exception e) {}  
               }  
               json.setCharAt(json.length() - 1, ‘}‘);  
             } else {  
               json.append("}");  
             }  
             return json.toString();  
  }

public static String list2json(List<?> list) {  
             StringBuilder json = new StringBuilder();  
             json.append("[");  
             if (list != null && list.size() > 0) {  
               for (Object obj : list) {  
                 json.append(object2json(obj));  
                 json.append(",");  
               }  
               json.setCharAt(json.length() - 1, ‘]‘);  
             } else {  
               json.append("]");  
             }  
             return json.toString();  
  }  

public static String array2json(Object[] array) {  
             StringBuilder json = new StringBuilder();  
             json.append("[");  
             if (array != null && array.length > 0) {  
               for (Object obj : array) {  
                 json.append(object2json(obj));  
                 json.append(",");  
               }  
               json.setCharAt(json.length() - 1, ‘]‘);  
             } else {  
               json.append("]");  
             }  
             return json.toString();  
  }

public static String map2json(Map<?, ?> map) {  
             StringBuilder json = new StringBuilder();  
             json.append("{");  
             if (map != null && map.size() > 0) {  
               for (Object key : map.keySet()) {  
                 json.append(object2json(key));  
                 json.append(":");  
                 json.append(object2json(map.get(key)));  
                 json.append(",");  
               }  
               json.setCharAt(json.length() - 1, ‘}‘);  
             } else {  
               json.append("}");  
             }  
             return json.toString();  
  }  

public static String set2json(Set<?> set) {  
             StringBuilder json = new StringBuilder();  
             json.append("[");  
             if (set != null && set.size() > 0) {  
               for (Object obj : set) {  
                 json.append(object2json(obj));  
                 json.append(",");  
               }  
               json.setCharAt(json.length() - 1, ‘]‘);  
             } else {  
               json.append("]");  
             }  
             return json.toString();  
  }  

public static String string2json(String s) {  
             if (s == null)  
               return "";  
             StringBuilder sb = new StringBuilder();  
             for (int i = 0; i < s.length(); i++) {  
               char ch = s.charAt(i);  
               switch (ch) {  
               case ‘"‘:  
                 sb.append("\\\"");  
                 break;  
               case ‘\\‘:  
                 sb.append("\\\\");  
                 break;  
               case ‘\b‘:  
                 sb.append("\\b");  
                 break;  
               case ‘\f‘:  
                 sb.append("\\f");  
                 break;  
               case ‘\n‘:  
                 sb.append("\\n");  
                 break;  
               case ‘\r‘:  
                 sb.append("\\r");  
                 break;  
               case ‘\t‘:  
                 sb.append("\\t");  
                 break;  
               case ‘/‘:  
                 sb.append("\\/");  
                 break;  
               default:  
                 if (ch >= ‘\u0000‘ && ch <= ‘\u001F‘) {  
                   String ss = Integer.toHexString(ch);  
                   sb.append("\\u");  
                   for (int k = 0; k < 4 - ss.length(); k++) {  
                     sb.append(‘0‘);  
                   }  
                   sb.append(ss.toUpperCase());  
                 } else {  
                   sb.append(ch);  
                 }  
               }  
             }  
             return sb.toString();  
  }  
}
web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<display-name></display-name>
	<servlet>
		<description>This is the description of my J2EE component</description>
		<display-name>This is the display name of my J2EE component</display-name>
		<servlet-name>showInfoServlet</servlet-name>
		<servlet-class>client_servlet.showInfoServlet</servlet-class>
	</servlet>
	<servlet>
		<description>This is the description of my J2EE component</description>
		<display-name>This is the display name of my J2EE component</display-name>
		<servlet-name>JsonServlet</servlet-name>
		<servlet-class>client_servlet.JsonServlet</servlet-class>
	</servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ajaxServlet</servlet-name>
    <servlet-class>client_servlet.ajaxServlet</servlet-class>
  </servlet>

	<filter>
		<filter-name>myFilter</filter-name>
		<filter-class>utils.CrossDomainFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>myFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<servlet-mapping>
		<servlet-name>showInfoServlet</servlet-name>
		<url-pattern>/servlet/showInfoServlet</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>JsonServlet</servlet-name>
		<url-pattern>/servlet/JsonServlet</url-pattern>
	</servlet-mapping>
  <servlet-mapping>
    <servlet-name>ajaxServlet</servlet-name>
    <url-pattern>/servlet/ajaxServlet</url-pattern>
  </servlet-mapping>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

用于处理业务逻辑的servlet:
package client_servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javabean.Route;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import services.RouteService;
import utils.JsonUtil;

public class showInfoServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
       doPost(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  response.setHeader("Access-Control-Allow-Origin","*");
		  response.setContentType("text/html; charset=UTF-8");//jsonp其实回写的就是一段JavaScript代码
		  PrintWriter out = response.getWriter();
		  //从数据库查询所有的路线route的集合list
		  RouteService rs = new RouteService();
		  String res = JsonUtil.list2json(rs.listAll());
		  out.print(res);
		  out.flush();
		  out.close();
	}
}

  

通过hbuilder建立的demo.html文件:

该文件用于请求后台的servlet并且接受服务器端返回的json数据

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />

<title>hello world</title>

<script src="http://www.mamicode.com/js/mui.min.js"></script>

<link href="http://www.mamicode.com/css/mui.min.css" rel="stylesheet" />

<script type="text/javascript">

if(window.plus) {

plusReady();

} else {

document.addEventListener("plusready", plusReady(), false);

}

 

function plusReady() {

 

}

//创建一个新的页面

function createNewWeb() {

var url = "http://www.jiangbobobo.cn/smart";

plus.webview.create(url).show();

}

//发送数据的函数

function postData(url, data, callback) {

mui.ajax(url, {

data: ‘data=http://www.mamicode.com/‘ + JSON.stringify(data),

dataType: ‘json‘,

type: ‘get‘,

contentType: "application/x-www-form-urlencoded; charset=utf-8",

timeout: 6000000,

success: callback,

error: function(xhr, type, errorThrown) {

//waitingDialog.close();

mui.alert("<网络连接失败,请重新尝试一下>", "错误", "OK", null);

console.log(type);

console.log(JSON.stringify(xhr));

}

});

}

 

function test() {

var data = http://www.mamicode.com/{};

postData(‘http://192.168.17.1:8080/zannadu/servlet/showInfoServlet‘,

data, // json 数据  

function(json) {

//mui.alert("hello");

var html = "";

var x = document.getElementById("mycard");

//mui.alert(str);

for(var i = 0; i < json.length; i++) {

//mui.alert(json[i].imageURL);

html += "<div class=‘mui-card‘>";

html += "<div class=‘mui-card-header mui-card-media‘ style=‘height:40vw;background-image:url(" + json[i].imageURL + ")‘></div>";

html += "<div class=‘mui-card-content‘>";

html += "<div class=‘mui-card-content-inner‘>";

html += "<div class=‘mui-content‘>";

html += "<h4>" + json[i].name + "</h4>";

html += "<p id=‘route_description‘>";

html += "" + json[i].service_content + "";

html += "</p>";

html += "</div>";

html += "</div>";

html += "</div>";

html += "<div class=‘mui-card-footer‘>";

html += "<a class=‘mui-card-link‘>" + json[i].like_number + "</a>";

html += "<a class=‘mui-card-link‘>" + json[i].old_price + "</a>";

html += "<a class=‘mui-card-link‘>" + json[i].new_price + "</a>";

html += "</div>";

html += "</div>";

x.innerHTML = html;

}

}

);

}

</script>

</head>

 

<body onl oad="test()">

<!--<button onclick="createNewWeb()">show data</button>-->

<!--<input type="button" value="http://www.mamicode.com/test" onclick="test()" />-->

<div class="mui-content" id="mycard">

</div>

</body>

</html>

ajax跨域访问数据