欢迎来到Java学习网!
设为首页 | 加入收藏
当前位置: 首页 > Java架构 > Servlet >

非常有用的防盗链图片的filter,还凑合着可以用下

web.xml:

<filter-mapping>
<filter-name>imageRedirectFilter</filter-name>
<url-pattern>/upload/images/*</url-pattern>
</filter-mapping>

源代码:

public class ImageRedirectFilter implements Filter {

public void init(FilterConfig config) throws ServletException {
}

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;

// 禁止缓存
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragrma", "no-cache");
response.setDateHeader("Expires", 0);

// 链接来源地址
String referer = request.getHeader("referer");
System.out.println("refer is"+referer);

if (referer == null || !referer.contains(request.getServerName())) {

/**
* 如果 链接地址来自其他网站,则返回错误图片
*/
request.getRequestDispatcher("/error.gif").forward(request, response);

} else {

/**
* 图片正常显示
*/
chain.doFilter(request, response);
}

}

public void destroy() {
}
}

    相关教程
    推荐内容