创建AProject和BProject两个工程
AProject工程
导入依赖
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
创建页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <img src="/img/logo.jpg" width="500px" height="300px" /> </body> </html>
创建ImgFilter类
package com.wn.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ImgFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("过滤器开始!!!"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //获取当前请求的连接地址和上一个发送请求的地址 HttpServletRequest httprequest=(HttpServletRequest) request; HttpServletResponse httpresponse=(HttpServletResponse) response; //获取上一个发送请求的连接 String referer = httprequest.getHeader("Referer"); String serverName = httprequest.getServerName(); System.out.println(referer+" "+serverName); //||!referer.startsWith("http://www.aproject.com") if (referer==null ||!referer.contains(serverName)){ request.getRequestDispatcher("/img/fei.png").forward(request,response); return; } //放行 chain.doFilter(request,response); } @Override public void destroy() { System.out.println("过滤器销毁!!!"); } }
配置web.xml文件
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <filter> <filter-name>ImgFilter</filter-name> <filter-class>com.wn.filter.ImgFilter</filter-class> </filter> <filter-mapping> <filter-name>ImgFilter</filter-name> <url-pattern>/img/*</url-pattern> </filter-mapping> </web-app>
BProject工程
创建页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <img src="http://www.aproject.com:8080/img/logo.png" width="500px" height="300px"/> </body> </html>
结果测试