在本地应用中访问http的远程服务器上的静态资源时,会遇到一个问题,就是远程页面中的静态资源的引用路径是相对的,这样请求的路径会自动加上本地应用的路径前缀,而不是http服务器的url前缀。
解决方法:
使用Spring的filter拦截对于远程资源的请求,这个请求路径可以任意指定,但最后是请求资源在远程服务器上的相对路径,为了便于filter拦截这样的远程请求路径,可以指定匹配http打头的url,比如filter在web.xml中可以这样配置:
<filter> <filter-name>httpResourcesFilter</filter-name> <filter-class>com.focoon.web.filter.HttpResourcesFilter</filter-class> </filter> <filter-mapping> <filter-name>httpResourcesFilter</filter-name> <url-pattern>/http/*</url-pattern> </filter-mapping>
java代码中可以对路径进行重新处理,并使用httpClient来访问远程的静态资源并在response中输出字节数组。
package com.focoon.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.web.filter.OncePerRequestFilter;
public class HttpResourcesFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
System.out.println("----------------------------拦截到了远程请求资源路径---------------------------------");
String url = request.getRequestURI();
String prefixRemoteUrl = "http://xxx.xxx.xxx.xxx/sns/unzip/";
String relativeRemoteUrl = url.substring(url.indexOf("http/")+5);
String remoteUrl = prefixRemoteUrl + relativeRemoteUrl;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(remoteUrl);
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
}
// 读取内容
byte[] responseBody = getMethod.getResponseBody();
// response.setHeader("Content-type","text/html;charset=UTF-8"); //指定消息头以UTF-8码表读数据
response.getOutputStream().write(responseBody);
}
}
最后是页面上的调用:
<body>
<iframe width="560px" height="620px" src="${ctx}/http/20150129190250/父母/index.html"></iframe>
</body>