1. 程式人生 > >springboot中編寫過濾器Filter以及配置

springboot中編寫過濾器Filter以及配置

  1. 簡單方式: 繼承Filter 以及 新增@component註解即可
    package com.imooc.demo.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
/**
 *  第一種方式:
 *  springboot中做過濾器 , 直接繼承filter , 新增component註解即可
 *  第二種方式 -> 如 MyFilter2 與 config包下 . 將第三方過濾器新增入過濾器鏈中
 *
 *  過濾器的缺點:
 *      1. 只能獲取request 與 response物件 . 並不能獲取要訪問的類與方法.
 *      2. 因為繼承的filter是servlet的 , 並不是spring的
 *      3. 可以使用spring提供的攔截器 intercept
 */
@Component public class MyFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init..."); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
IOException, ServletException { System.out.println("過濾器...."); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { System.out.println("毀滅中..."); } }

2.1. 可配置方式.,通過使用@configuration註解實現

package com.imooc.demo.filter;

import
org.springframework.stereotype.Component; import javax.servlet.*; import java.io.IOException; /** * */ public class MyFilter2 implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("init..."); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("過濾器...."); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { System.out.println("毀滅中..."); } }

2.2 webconfig配置物件

package com.imooc.demo.filter.config;
import com.imooc.demo.filter.MyFilter2;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class Webconfig {
    /**
     *  配置自定義過濾器或者第三方提供的過濾器
     * @return
     */
    @Bean
    public FilterRegistrationBean MyFilter() {
        // 此物件效果等同於 web.xml中的過濾器的配置
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        MyFilter2 myFilter2 = new MyFilter2();
        filterRegistrationBean.setFilter(myFilter2);
        // 指定過濾url
        List<String> urls = new ArrayList<>();
        urls.add("/*");
        filterRegistrationBean.setUrlPatterns(urls);
        return filterRegistrationBean;
    }
}