一个小小的防盗链图片的filter,还凑合着可以用下
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() {
}
}
web.xml:
<filter-mapping>
<filter-name>imageRedirectFilter</filter-name>
<url-pattern>/upload/images/*</url-pattern>
</filter-mapping>