13.自定义拦截器

1.使用Servlet3.0的注解进行配置 2.启动类里面增加 @ServletComponentScan,进行扫描 3.自定义拦截器(适合前后端未分离的应用场景)

/** * 自定义拦截器(适合前后端未分离的应用场景) * urlPatterns 拦截api的请求 * filterName 拦截器别名 * @author Administrator * */ @WebFilter(urlPatterns = "/api/*",filterName = "loginfilter") public class LoginFilter implements Filter{/** * 拦截请求 */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("进入自定义拦截器"); HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String username = req.getParameter("username"); if("ll".equals(username)) { chain.doFilter(request, response); //控制chain.doFilter的方法的调用,来实现是否通过放行 }else { //不做任何处理直接拦截返回 return; } }}

【13.自定义拦截器】注:1.@WebFilter 标记一个类为filter,被spring进行扫描
2.urlPatterns:拦截规则,支持正则

    推荐阅读