美文网首页
Springboot支持filter(过滤器)

Springboot支持filter(过滤器)

作者: 庙人 | 来源:发表于2018-12-19 18:40 被阅读0次

    1:定义filter类

    package com.duck.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    
    @WebFilter(filterName = "duckFilter",urlPatterns = "/filter/*")
    public class DuckFilter implements javax.servlet.Filter {
    
        public void init(FilterConfig filterConfig) throws ServletException {
            // TODO Auto-generated method stub
    
        }
    
        public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest)request;
            System.out.println(req.getRequestURL() + "------>doFilter");
            chain.doFilter(request, response);
        }
    
        public void destroy() {
            // TODO Auto-generated method stub
    
        }
    
    }
    

    2:定义启动类 @ServletComponentScan

    package com.duck.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    
    @WebFilter(filterName = "duckFilter",urlPatterns = "/filter/*")
    public class DuckFilter implements javax.servlet.Filter {
    
        public void init(FilterConfig filterConfig) throws ServletException {
            // TODO Auto-generated method stub
    
        }
    
        public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest)request;
            System.out.println(req.getRequestURL() + "------>doFilter");
            chain.doFilter(request, response);
        }
    
        public void destroy() {
            // TODO Auto-generated method stub
    
        }
    
    }
    

    3:访问定义的urlmapping,后台就会调用到filter
    此例可访问 http://localhost:8080/filter,后台打印日志

    image.png

    相关文章

      网友评论

          本文标题:Springboot支持filter(过滤器)

          本文链接:https://www.haomeiwen.com/subject/rgxskqtx.html