servlet实现防盗链
时间: 2024-01-10 11:16:22 浏览: 110
java 防盗链详解及解决办法
防盗链是指通过判断HTTP请求的Referer头信息来限制或拒绝非法的站点访问资源。在Servlet中实现防盗链可以通过获取请求头中的Referer,并与允许的站点进行比较来判断是否为合法的访问。以下是一个简单的实现示例:
```java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AntiLeechServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String referer = request.getHeader("referer");
if (referer == null || !referer.startsWith("http://www.example.com")) {
// 如果referer为空或者不是合法的访问来源,返回错误信息
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("<h1>盗链可耻!!!</h1>");
} else {
// 合法的访问来源,返回正常内容
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("<h1>欢迎访问^_^!!</h1>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
阅读全文