本例中的过滤器防止通过浏览器的地址栏直接输入图片的URL来下载图片。只有在页面中点击图片的链接时,才会显示程序中的图片。
过滤器通过查看HTTP标头的referer的值进行工作。值为空表示当前没有相当的引用页,也就是说,该资源是直接输入URL进行请求的。
public class Image implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("Image");
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String referer = httpServletRequest.getHeader("referer");
System.out.println("referer:"+referer);
if(referer != null){
filterChain.doFilter(request, response);
}else{
throw new ServletException("Image not avaliable");
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
部署描述符
<filter>
<filter-name>Image</filter-name>
<filter-class>filter.Image</filter-class>
</filter>
<filter-mapping>
<filter-name>Image</filter-name>
<url-pattern>*.png</url-pattern>
</filter-mapping>
直接访问图片目录时:
添加一个image.jsp文件
里面包含了引导浏览器下载图片的链接
<image src="image/1.png"/>
访问image.jsp