filter图片防盗链

        防盗链Filter实现这样一种效果,如果其他网站通过链接引用本网站的图片资源,将会显示一个错误页面。只有本站内的网页引用时,图片才会正常显示,即在图片显示之前对request进行验证,看客户请求是否来自本网站内,代码如下:

@WebFilter(filterName = "ImageFilter")
public class ImageFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        String referer = request.getHeader("referer");
        //如来自其他网站的请求
        if(referer == null||!referer.contains(request.getServerName())){
            request.getRequestDispatcher("/error/error.jsp").forward(request,response);
        }else{
            chain.doFilter(request, response);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

        改Filter从request信息头中获取请求来自何方,Filter的配置代码如下:


        imgageFilter
        filter.ImageFilter
    
    
        imgageFilter
        /images/*
    

        改Filter配置表明对"/images/"下面的所有资源进行防盗链过滤处理。运行效果如下:

正常链接:

filter图片防盗链_第1张图片

非正常链接

filter图片防盗链_第2张图片

你可能感兴趣的:(jsp)