使用步骤:
1.建立Filter类。实现Filter接口
@WebFilter(filterName = "test", urlPatterns = "/success/*")
public class UrlFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("----------------------->过滤器被创建");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
String requestURI = req.getRequestURI();
System.out.println("--------------------->过滤器:请求地址"+requestURI);
if(!requestURI.contains("info")){
servletRequest.getRequestDispatcher("/failed").forward(servletRequest, servletResponse);
}else{
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Override
public void destroy() {
System.out.println("----------------------->过滤器被销毁");
}
}
2.为Filter加注解。
3。在主类上加包扫描。