关耳er  

一、目录展示

  分为AProject和BProject两个项目进行测试

  

二、修改c:\windows\system32\drivers\etc下的hosts文件

  

三、aindex.jsp

  

四、bindex.jsp

   

五、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <filter>
        <filter-name>imgFilter</filter-name>
        <filter-class>com.zn.ImageFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>imgFilter</filter-name>
        <url-pattern>/img/*</url-pattern>
    </filter-mapping>

</web-app>

六、ImageFilter

package com.zn;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ImageFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器启动!");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("走了吗");
        //获取到当前请求的连接地址和上一个发送请求的地址
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;

        //获取上一个发送请求的连接
        String referer=request.getHeader("Referer");
        String serverName = request.getServerName();
        System.out.println(referer+"\thhhh\t"+serverName);

        if (referer==null||!referer.contains(serverName)){
            request.getRequestDispatcher("/img/ff.png").forward(request,response);
            return;
        }

        //放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        System.out.println("过滤器销毁!");
    }
}

七、效果展示

  1、访问AProject项目可以访问

  

  2、拦截以后使用b.com的BProject的访问为非法访问

  

 

posted on 2020-02-04 17:26  关耳er  阅读(245)  评论(0编辑  收藏  举报