Springboot支持filter(过滤器)

2018-12-19  本文已影响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
上一篇下一篇

猜你喜欢

热点阅读