防止盗链

1.创建类

package com.hbxy.web.c02.request;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class DownManagerServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
// ??获取referer头的值???
        String referer = request.getHeader("referer");
// ??????获取访问地址
        String sitePart = "http://" + request.getServerName();
// ??判断refer头是否为空,这个投的首地址是否是已???????????????sitePart???开始
        if (referer != null && referer.startsWith(sitePart)) {
// ?????????处理正在下载的请求
            out.println("dealing download ...");
        } else {
// ?????????非法请求跳转到download.html??页面
            RequestDispatcher rd = request.getRequestDispatcher("/myweb/download.html");
            rd.forward(request, response);
        }
    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

2.创建download.html




    
    ??下载


??下载

3.配置web.xml






  
    DownManagerServlet
    com.hbxy.web.c02.request.DownManagerServlet
  
  
    DownManagerServlet
    /DownManagerServlet
  

测试

????只通过download.html才能下载;如果直接访问 ?????????? ?DownManagerServlet 将跳转到 ???????download.html?

防止盗链_第1张图片

 

你可能感兴趣的:(Java,Web)