jsp允许跨域访问_js跨域访问解决方法(jsp代理)

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

proxy.jsp源码:

String url = null;

StringBuffer params = new StringBuffer();

Enumeration enu = request.getParameterNames();

//String str=request.getQueryString();

//System.out.println(str);

int total = 0;

while (enu.hasMoreElements()) {

String paramName=(String)enu.nextElement();

if(paramName.equals("url")){

url=request.getParameter(paramName);

}else{

//request.getParameterNames()取得的参数顺序是随机的//若是用get方式发送的,可以用request.getQueryString()方式获得

if(total==0){

params.append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));

} else {

params.append("&").append(paramName).append("=").append(URLEncoder.encode(request.getParameter(paramName), "UTF-8"));

}

++total;

}

}

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;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值