日期:2014-05-16  浏览次数:20346 次

js跨域访问解决方法(jsp代理)

? ? ? 在javascript中通过xmlhttprequest跨域访问其他资源会被浏览器阻止,因为跨域访问容易引起安全问题。对于要访问的资源那端不能被修改的情况(要访问的资源的服务器不能被修改的情况),可以通过jsp代理来实现跨域的访问,因为jsp没有跨域访问问题。例如www.A.html要访问www.B.html,先让A.html访问proxy.jsp,proxy.jsp在转发到B.html。

? ? ? proxy.jsp源码:

<%@ page import="java.net.*,java.util.*,java.lang.*,java.io.*"%><%@ page contentType="text/xml;charset=gb2312"%><%  
String url = null;
StringBuffer params = new StringBuffer();
Enumeration enu = request.getParameterNames();
//String str=request.getQueryString();
//System.out.println(str);

while (enu.hasMoreElements()) {
String paramName=(String)enu.nextElement();
if(paramName.equals("url")){
   url=request.getParameter(paramName);
}else{
   //有的url参数顺序有规定,按此读出的是逆序,因此要插到paramName的前面
   params.insert(0, URLEncoder.encode(request.getParameter(paramName), "UTF-8"));
   params.insert(0, "=");
   params.insert(0, paramName);
   if(enu.hasMoreElements()){
	   params.insert(0, "&");
   }
}
}
url = url + "?" + params.toString();
//out.println(url);
System.out.println("url:"+url);

if(url != null){
// 使用GET方式向目的服务器发送请求
URL connect = new URL(url.toString());
URLConnection connection = connect.openConnection();
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while((line = reader.readLine()) != null){
   out.println(line);
}
reader.close();
}
%>

? ? javascript端源码:

var thr;
function getanswer(){
    try{
alert(thr.responseText);
    }catch(e){
    	alert("getanswer error:"+e.message);
    }
    
    }

function testone(){
	try{
		thr = createXMLRequestObj();
	var url = "proxy.jsp?url=http://192.168.2.101:80/ScanWlan.cgi?NAME=WANG";
	var param="name=wang";
	//alert("first readystate:"+thr.readyState+" status:");
	thr.open ("GET", url, true);
	thr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//上面这句不可少啊!!!!!!!!!!!!!!!
	thr.onreadystatechange=getanswer;
	if(thr==null){
		alert("not create sucess");
		return;
	}
	thr.send(null);
	}catch(e){
		alert("error"+e.message);
	}
}
function createXMLRequestObj(){
    var xmlReqObj = null;

    if (xmlReqObj == null){
	    try {xmlReqObj = new XMLHttpRequest();}//非IE
	    catch (e) {xmlReqObj = null;}
    }
    if (xmlReqObj == null){
	    try {xmlReqObj = new ActiveXObject("Msxml2.XMLHTTP");}
	    catch (e) {xmlReqObj = null;}
    }
    if (xmlReqObj == null){
	    try {xmlReqObj = new ActiveXObject("Microsoft.XMLHTTP");}
	    catch (e) {xmlReqObj = null;}
    }
    return xmlReqObj;
}

?