1. 程式人生 > >springboot 使用Filter

springboot 使用Filter

implement alt orf err script string sep tro class a

1. 創建 Filter 類,實現 Fitler接口

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @Auther: Dandwj
 * @Date: 2019/3/20 23:00
 * @Description: 
 */
@WebFilter(filterName = "myFilter",urlPatterns = "/login/*")
public class AuthorFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //處理請求
        
        filterChain.doFilter(servletRequest, servletResponse);
    }
    @Override
    public void destroy() {

    }
}

然後加上 @WebFilter 註解

2. 在啟動類上加上@ServletComponentScan(basePackages = "pers.dandwj.cheerful.service")註解 MyFilter 是在 basePackages包下

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @ServletComponentScan(basePackages = "pers.dandwj.cheerful.service") public class CheerfulWxApiApplication { public static void main(String[] args) { SpringApplication.run(CheerfulWxApiApplication.
class, args); } }

擴展:

三種攔截器比較:

技術分享圖片

  • Filter 是 java web 裏面的,肯定獲取不到 spring 裏面 Controller 的信息。
  • Interceptor、Aspect 是和 spring 相關的,所以能獲取到 Controller 的信息。

springboot 使用Filter