什么是Referer?
Referer是header的一部分,当浏览器向服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理。
什么是非法链接?
1)直接访问资源 (Referer=null)
2)B网站盗用A网站的资源
怎样防止非法链接?
写一个过滤器 获取每次请求头中的Referer 然后判断Referer中的来源值。如果来源值为空或者不是本站域名,说明是非法链接,要进行拦截;如果来源值是本站域名,则放行。
代码演示:
A页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>A页面</title>
</head>
<body>
<img alt="" width="200px" src="imgs/log1.png">
</body>
</html>
B页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>B页面</title>
</head>
<body>
<img alt="" width="200px" src="http://localhost:8080/Http/imgs/log1.png">
</body>
</html>
RefererFilter(拦截器):
/**
* 功能描述:(防止非法链接)
*/
public class RefererFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
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");
if (referer == null || !referer.contains("http://localhost:8080/Http/A.jsp")) {
req.getRequestDispatcher("/imgs/error.png").forward(req, res);
return;
}
chain.doFilter(req, res);//放行
}
public void destroy() {
}
}
web.xml配置:
<filter>
<filter-name>RefererFilter</filter-name>
<filter-class>zzuli.edu.cn.RefererFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RefererFilter</filter-name>
<url-pattern>/imgs/*</url-pattern>
</filter-mapping>
运行结果: