Java Web利用Referer头字段实现防盗链

package cn.itcast.chapter04.request;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
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 DownManagerServlet
 */
@WebServlet("/DownManagerServlet")
public class DownManagerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownManagerServlet() {
        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.setContentType("text/html;charset=utf-8");
		PrintWriter out =response.getWriter();
		//获取referer头的值
		String referer=request.getHeader("referer");
		//获取访问地址
		String sitePart="http://"+request.getServerName();
		//判断refeer头是否为空,这个头的首地址是否以siteName开始的
		if(referer!=null&& referer.startsWith(sitePart)){
			//处理正在下载的请求
			out.println("dealing downloa...");
		}
		else{
			//非法下载请求跳转到dawnload.html页面
			RequestDispatcher rd=request.getRequestDispatcher("/download.html");
			rd.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);
	}

}

Java Web利用Referer头字段实现防盗链_第1张图片
Java Web利用Referer头字段实现防盗链_第2张图片

你可能感兴趣的:(Java,Web,java,前端,开发语言)