java使用代理解决跨域问题

为什么需要proxy.jsp代理文件

由于浏览器实现的同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源,所以AJAX是不允许跨域访问的。为了解决这一问题,我们使用java代码来访问服务。当javascript发出一个请求,首先访问本地的java代码,然后调用我们的服务。proxy.jsp就是实现这一过程的java代码。

如何配置代理文件

1.在项目的根目录下创建proxy.jsp文件。该文件内容如下

 <%@ page import="java.io.*" %>
    <%@ page import="java.net.URL" %>

    <%@ page import="java.net.HttpURLConnection" %>
    <%@  page  session="false"  %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>

    <%!

        void copy(InputStream in, OutputStream out, boolean save) throws IOException {
            try{
                byte[] buffer = new byte[1024];
                int count = 0;
                while((count =in.read(buffer)) > 0){
                out.write(buffer,0,count);
                 }
            }
            finally {
                out.close();
                in.close();
            }
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String reqUrl =  request.getQueryString();
            URL url = new URL(reqUrl);

            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setDoOutput(false);
            con.setRequestMethod("GET");


            response.setContentType(con.getContentType());
            OutputStream out = response.getOutputStream();
            InputStream in = con.getInputStream();
            copy(in,out,false);
        }


         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String reqUrl =  request.getQueryString();
            URL url = new URL(reqUrl);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setDoOutput(true);
            con.setRequestMethod("POST");

            if(request.getContentType() != null) {
                con.setRequestProperty("Content-Type", request.getContentType());
            }
            OutputStream destCout = con.getOutputStream();
            copy(request.getInputStream(),destCout,true);

            InputStream in = con.getInputStream();
            OutputStream out = response.getOutputStream();
            copy(in,out,false);
        }

    %>

    <%
         out.clear();
        out = pageContext.pushBody();
        String method  = request.getMethod();
        if("GET".equals(method)){
            doGet(request,response);
        }
        else if("POST".equals(method)){
            doPost(request,response);
        }
    %>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值