1这次练习中一直受到相对路径的干扰,现在澄清一点
forward中不是不需要包含根目录的 比如 http://localhost:8080/filter/upload/images/no.jpg
你只要写到 (/upload/images/no.jpg)就好
而在html中是需要根目录的
2根据referer判断是否自己网站发出的请求
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+"/";%>My JSP 'show.jsp' starting page <% %>dsf
直接访问d 直接访问ok 直接访问no
模拟直接访问