1此次練習中一直受到相對路徑的干擾,如今澄清一點css
forward中不是不須要包含根目錄的 好比 http://localhost:8080/filter/upload/images/no.jpghtml
你只要寫到 (/upload/images/no.jpg)就好java
而在html中是須要根目錄的jsp
<img src="<%=request.getContextPath()%>/images/ok.jpg" /></div> <a href="<%=request.getContextPath()%>/d.jpg">直接訪問d</a> <a href="<%=request.getContextPath()%>/images/ok.jpg">直接訪問ok</a> <a href="<%=request.getContextPath()%>/upload/images/no.jpg">直接訪問no</a>
2根據referer判斷是否本身網站發出的請求ide
String referer = req.getHeader("referer"); if (referer == null || !referer.contains(req.getServerName())) {
源碼網站
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest req = (HttpServletRequest) request;// 注意上面是接口servletRequest/response HttpServletResponse res = (HttpServletResponse) response; String referer = req.getHeader("referer"); if (referer == null || !referer.contains(req.getServerName())) { req.getRequestDispatcher("/d.jpg").forward(req, res); } else { chain.doFilter(request, response); } } @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'show.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <% %> </head> <body> <p>dsf</p> <div class="zj02"><img src="<%=request.getContextPath()%>/images/ok.jpg" /></div> <a href="<%=request.getContextPath()%>/d.jpg">直接訪問d</a> <a href="<%=request.getContextPath()%>/images/ok.jpg">直接訪問ok</a> <a href="<%=request.getContextPath()%>/upload/images/no.jpg">直接訪問no</a> </body> </html>
模擬直接訪問ui
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <a href="http://localhost:8080/filter/d.jpg">直接訪問d</a> <a href="http://localhost:8080/filter/images/ok.jpg">直接訪問ok</a> <a href="http://localhost:8080/filter/upload/images/no.jpg">直接訪問no</a> </body> </html>