防盗链图片的filter的问题。
防盗链图片的filterpublic class ImageRedirectFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 禁止缓存
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragrma", "no-cache");
response.setDateHeader("Expires", 0);
// 链接来源地址
String referer = request.getHeader("referer");
System.out.println("refer is"+referer);
if (referer == null || !referer.contains(request.getServerName())) {
/**
* 如果 链接地址来自其他网站,则返回错误图片
*/
request.getRequestDispatcher("/error.gif").forward(request,response);
} else {
/**
* 图片正常显示
*/
chain.doFilter(request, response);
}
}
public void destroy() {
}
}
/////////////////////////////////////////////////////
web.xml:
<filter-mapping>
<filter-name>imageRedirectFilter</filter-name>
<url-pattern>/upload/images/*</url-pattern>
</filter-mapping>
问题:红色的那句并不能请求转移而显示error.gif的图片。
必须将红色的那句写成:request.getRequestDispatcher("error.jsp").forward(request,response);
在error.jsp中再显示error.gif图片才可以,为什么?
error.jsp内容如下:
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'error.jsp' starting page</title>
</head>
<body>
<%=path %><br>
<%=basePath %><br>
<img src="error.gif">
</body>
</html>