为什么需要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);
}
%>