1. 程式人生 > 程式設計 >springboot 增加過濾器方法操作示例

springboot 增加過濾器方法操作示例

本文例項講述了springboot 增加過濾器方法操作。分享給大家供大家參考,具體如下:

在訪問伺服器時,我們需要控制使用者是否允許許可權,這個時候可以使用過濾器。

在springboot 配置過濾器的方法如下:

編寫過濾器程式碼:

package com.neo.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter {
  @Override
  public void destroy() {
  }
  @Override
  public void doFilter(ServletRequest srequest,ServletResponse sresponse,FilterChain filterChain)
      throws IOException,ServletException {
    HttpServletRequest request = (HttpServletRequest) srequest;
    System.out.println("this is MyFilter,url :"+request.getRequestURI());
    filterChain.doFilter(srequest,sresponse);
  }
  @Override
  public void init(FilterConfig arg0) throws ServletException {
  }
}

編寫載入過濾器程式碼:

package com.neo.conf;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.neo.filter.MyFilter;
import com.neo.filter.MyFilter2;
@Configuration
public class WebConfiguration {
  @Bean
  public FilterRegistrationBean registerFilter() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new MyFilter());
    registration.addUrlPatterns("/*");
    registration.addInitParameter("paramName","paramValue");
    registration.setName("MyFilter");
    registration.setOrder(1);
    return registration;
  }
  @Bean
  public FilterRegistrationBean registerFilter2() {
    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new MyFilter2());
    registration.addUrlPatterns("/*");
    registration.addInitParameter("paramName","paramValue");
    registration.setName("MyFilter2");
    registration.setOrder(2);
    return registration;
  }
}

這裡我們看到我們註冊了兩個過濾器,過濾器的執行順序通過setOrder確定。

更多關於java相關內容感興趣的讀者可檢視本站專題:《Spring框架入門與進階教程》、《Java資料結構與演算法教程》、《Java操作DOM節點技巧總結》、《Java檔案與目錄操作技巧彙總》和《Java快取操作技巧彙總》

希望本文所述對大家java程式設計有所幫助。