`
wanchong998
  • 浏览: 236044 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

javaweb使用过滤器防止图片盗链 ------请求头referer的使用

 
阅读更多

在web.xml文件中如下配置:

 

  1.  
    <filter>
  2.  
    <filter-name>SimpleFilter</filter-name>
  3.  
    <filter-class>cn.SimpleFilter</filter-class>
  4.  
    </filter>
  5.  
    <filter-mapping>
  6.  
    <filter-name>SimpleFilter</filter-name>
  7.  
    <url-pattern>/images/*</url-pattern>
  8.  
    </filter-mapping>



 

在servlet过滤器代码如下:

 

  1.  
    package cn;
  2.  
     
  3.  
    import java.io.IOException;
  4.  
     
  5.  
    import javax.servlet.Filter;
  6.  
    import javax.servlet.FilterChain;
  7.  
    import javax.servlet.FilterConfig;
  8.  
    import javax.servlet.ServletException;
  9.  
    import javax.servlet.ServletRequest;
  10.  
    import javax.servlet.ServletResponse;
  11.  
    import javax.servlet.http.HttpServlet;
  12.  
    import javax.servlet.http.HttpServletRequest;
  13.  
    import javax.servlet.http.HttpServletResponse;
  14.  
     
  15.  
    public class SimpleFilter extends HttpServlet implements Filter {
  16.  
     
  17.  
    private static final long serialVersionUID = 1L;
  18.  
    private FilterConfig filterConfig;
  19.  
     
  20.  
    public void init(FilterConfig config) {
  21.  
    this.filterConfig = config;
  22.  
    }
  23.  
     
  24.  
    public void doFilter(ServletRequest req, ServletResponse res,
  25.  
    FilterChain chain) throws ServletException, IOException {
  26.  
     
  27.  
    HttpServletRequest request = (HttpServletRequest) req;
  28.  
    HttpServletResponse response = (HttpServletResponse) res;
  29.  
    // 禁止缓存
  30.  
    response.setHeader("Cache-Control", "no-store");
  31.  
    response.setHeader("Pragrma", "no-cache");
  32.  
    response.setDateHeader("Expires", 0);
  33.  
    // 链接来源地址
  34.  
    String referer = request.getHeader("referer");
  35.  
    System.out.println("refer is"+referer);
  36.  
    System.out.println("serverName is"+request.getServerName());
  37.  
    if (referer == null || !referer.contains(request.getServerName())) {
  38.  
    /**
  39.  
    * 如果 链接地址来自其他网站,则返回错误图片
  40.  
    */
  41.  
    request.getRequestDispatcher("/error.jsp").forward(request, response);
  42.  
    } else {
  43.  
    /**
  44.  
    * 图片正常显示
  45.  
    */
  46.  
    chain.doFilter(request, response);
  47.  
    }
  48.  
    }
  49.  
     
  50.  
    public void destroy() {
  51.  
    this.filterConfig = null;
  52.  
    }
  53.  
     
  54.  
    }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics