您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關SpringBoot怎么整合Filter,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
com.zhl.springbootweb.filter.FirstFilter
urlPatterns 可以指定后綴 或者 URL
實現@WebFilter注解
集成javax.servlet中的 Filter
package com.zhl.springbootweb.filter;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import java.io.IOException;/*整合Filter方式一*///@WebFilter(filterName = "first Filter",urlPatterns = {"*.do","*.jsp"})@WebFilter(filterName = "first Filter",urlPatterns = {"/first"})public class FirstFilter implements Filter {@Override public void init(FilterConfig filterConfig) throws ServletException { }@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("進入First Filter");/*放行*/ filterChain.doFilter(servletRequest,servletResponse); System.out.println("離開First Filter"); }@Override public void destroy() { } }
@ServletComponentScan
@SpringBootApplication /*在SpringBoot啟動時會掃描@WebServlet,@WebFilter注解,并將該類實例化*/ @ServletComponentScan public class SpringbootWebApplication { public static void main(String[] args) { SpringApplication.run(SpringbootWebApplication.class, args); } }
訪問localhost:8080/first
進入First Filter First Servlet 離開First Filter
com.zhl.springbootweb.filter.SecondFilter
package com.zhl.springbootweb.filter;import javax.servlet.*;import java.io.IOException;/** 整合Filter 方式二* */public class SecondFilter implements Filter {@Override public void init(FilterConfig filterConfig) throws ServletException { }@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("進入SecondFilter");/*放行*/ filterChain.doFilter(servletRequest,servletResponse); System.out.println("離開SecondFilter"); }@Override public void destroy() { } }
/*Filter 配置類*/@Configurationpublic class FilterConfig {@Bean public FilterRegistrationBean getFilterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());//bean.addUrlPatterns(new String[]{"*.do","*.jsp"}); bean.addUrlPatterns("/second");return bean; } }
訪問 http://localhost:8080/second
進入SecondFilter Second Servlet 離開SecondFilter
關于SpringBoot怎么整合Filter就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。