web页面防盗链功能使用--request.getHeader("referer")



import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RefererServlet
 */
@WebServlet("/RefererServlet")
public class RefererServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public RefererServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        //referer为客户端带来的请求头          
        String referer = request.getHeader("referer");  
        System.out.println(referer);  
        //如果链接出自地址栏的输入,则跳转至本站点RequestAndResponse应用的首页  
        if (referer==null) {  
            System.out.println("由于您访问的内容版权所有,您是地址栏上输入的链接,即将跳转至本站首页...");  
            response.sendRedirect("/Servlet_test1/index.html");  
            return ;  
        }  
        //如果链接出自本站点的RequestAndResponse应用的页面,则正常显示,如果是出自其他站点或本站点的其他应用,则跳转至本站点RequestAndResponse应用的首页  
        if(!referer.startsWith("http://localhost:8080/Servlet_test1")){  
            System.out.println("由于您访问的内容版权所有,您是其他网站页面的链接,即将跳转至本站首页...");  
            response.sendRedirect("/Servlet_test1/index.html");  
            return ;  
        }else {  
            System.out.println("来自本站页面的链接,合法用户");  
            request.getRequestDispatcher("content.jsp").forward(request, response);  
        }  
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

你可能感兴趣的:(web页面防盗链功能使用--request.getHeader("referer"))