java web笔记之Filter防盗链

1.防盗链简介

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

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class myFilter
 */
@WebFilter("/myFilter")
public class imageRedirectFilter implements Filter {

    /**
     * Default constructor. 
     */
    public imageRedirectFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String referer = req.getHeader("referer");
		System.out.println("referer=="+referer);
		System.out.println("req.getServerName()=="+req.getServerName());
		System.out.println("req.getServerName()=="+(referer == null || !referer.contains(req.getServerName())));
		if(referer == null || !referer.contains(req.getServerName())){
			req.getRequestDispatcher("/images/error.gif").forward(req, res);
		}else{
			chain.doFilter(req, res);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>




Insert title here





正确访问

直接在浏览器上输入网址访问会显示错误图片
从jsp访问会显示正确图片


你可能感兴趣的:(java)