当前访客身份:游客 [ 登录  | 注册加入尚学堂]
直播
新闻资讯

servlet解决浏览器的跨域

robert 发表于 1年前  | 评论(1 )| 阅读次数(618 )|   0 人收藏此文章,   我要收藏

概述:

在做一些web请求时,会涉及到很麻烦的浏览器跨域问题,因此,一般都会通过后台处理再给前台。本文讲述通过servlet解决浏览器的跨域问题。


实现:

在工程下新建一个servlet,实现代码如下:

package lzugis.web.agent;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class WebAgent
 */
@WebServlet(name="WebAgent",urlPatterns="/web/agent")
public class WebAgent extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String debug = "false";

    /**
     * Default constructor. 
     */
    public WebAgent() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String encoding = getInitParameter("encoding");
	    if ((encoding != null) && (!"".equals(encoding))) {
	      request.setCharacterEncoding(encoding);
	    }
	    String url = request.getParameter("url");
	    if (!"".equals(url)) {
	      responseFile(request, response, url);
	      return;
	    }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String encoding = getInitParameter("encoding");
	    if ((encoding != null) && (!"".equals(encoding))) {
	      request.setCharacterEncoding(encoding);
	    }
	    String url = request.getParameter("url");
	    if (!"".equals(url)) {
	      responseFile(request, response, url);
	      return;
	    }

	    if ("true".equals(this.debug)) {
	    	String data = readXMLFromRequestBody(request);
	    	System.out.println(data);
	    }
	}
	
	public void responseFile(HttpServletRequest req, HttpServletResponse resp, String url) {
	    try {
	      URL u = new URL(url);

	      URLConnection urlc = u.openConnection();
	      urlc.setConnectTimeout(3000);
	      urlc.setReadTimeout(100000);

	      resp.setContentType(urlc.getContentType());

	      ServletOutputStream out = null;
	      BufferedInputStream input = null;
	      byte[] data = new byte[1024];
	      int length = -1;
	      input = new BufferedInputStream(urlc.getInputStream());
	      out = resp.getOutputStream();
	      while ((length = input.read(data)) != -1) {
	        out.write(data, 0, length);
	      }
	      input.close();
	      out.flush();
	      out.close();
	    }
	    catch (IOException localIOException)
	    {
	    }
	  }

	  private String readXMLFromRequestBody(HttpServletRequest request) {
	    StringBuffer strBuf = new StringBuffer();
	    try {
	      BufferedReader reader = request.getReader();
	      String line = null;
	      while ((line = reader.readLine()) != null)
	        strBuf.append(line).append("\n");
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	    return strBuf.toString();
	  }
}
说明:

servlet是通过注解的方式配的,访问路径为:localhost:8080/lzugis/web/agent?url=http://localhost:6080/arcgis/rest/services/?f=pjson。

分享到:0
关注微信,跟着我们扩展技术视野。每天推送IT新技术文章,每周聚焦一门新技术。微信二维码如下:
微信公众账号:尚学堂(微信号:bjsxt-java)
声明:博客文章版权属于原创作者,受法律保护。如果侵犯了您的权利,请联系管理员,我们将及时删除!
(邮箱:webmaster#sxt.cn(#换为@))
北京总部地址:北京市海淀区西三旗桥东建材城西路85号神州科技园B座三层尚学堂 咨询电话:400-009-1906 010-56233821
Copyright 2007-2015 北京尚学堂科技有限公司 京ICP备13018289号-1 京公网安备11010802015183