解决springboot中配置过滤器以及可能出现的问题
在springboot添加过滤器有两种方式:
1、通过创建FilterRegistrationBean的方式(建议使用此种方式,统一管理,且通过注解的方式若不是本地调试,如果在filter中需要增加cookie可能会存在写不进前端情况)
2、通过注解@WebFilter的方式
通过创建FilterRegistrationBean的方式创建多个filter以及设置执行顺序:
1、创建两个实现Filter接口的类TestFilter1、TestFilter2
packagecom.aoxun.core.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; publicclassTestFilter1implementsFilter{ @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{} @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain) throwsIOException,ServletException{ chain.doFilter(request,response); } @Override publicvoiddestroy(){} }
packagecom.aoxun.core.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; publicclassTestFilter2implementsFilter{ @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{} @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain) throwsIOException,ServletException{ chain.doFilter(request,response); } @Override publicvoiddestroy(){} }
2、创建配置类
有多个filter就创建多个FilterRegistrationBean,若需注明filter的执行顺序,可通过registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE-1)配置,值越大,执行顺序越靠后
packagecom.aoxun.config.web; importorg.springframework.boot.web.servlet.FilterRegistrationBean; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importcom.aoxun.core.filter.TestFilter1; importcom.aoxun.core.filter.TestFilter2; /** *filter配置 *@authorzcj * */ @Configuration publicclassFilterConfig2{ @Bean publicFilterRegistrationBeancompanyUrlFilterRegister(){ FilterRegistrationBeanregistration=newFilterRegistrationBean(); //注入过滤器 registration.setFilter(newTestFilter1()); //拦截规则 registration.addUrlPatterns("/*"); //过滤器名称 registration.setName("testFilter1"); //过滤器顺序 registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); returnregistration; } @Bean publicFilterRegistrationBeanoutLinkSecurityFilterRegister(){ FilterRegistrationBeanregistration=newFilterRegistrationBean(); //注入过滤器 registration.setFilter(newTestFilter2()); //拦截规则 registration.addUrlPatterns("/*"); //过滤器名称 registration.setName("testFilter2"); //过滤器顺序 registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE-1); returnregistration; } }
通过注解@WebFilter的方式
1、在启动类上增加@ServletComponentScan注解,自动扫描带有过滤器注解的包
2、在类上使用@WebFilter
packagecom.aoxun.core.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.annotation.WebFilter; importorg.springframework.boot.web.servlet.FilterRegistrationBean; importorg.springframework.core.annotation.Order; @WebFilter(filterName="testFilter1",urlPatterns={"/*"}) publicclassTestFilter1implementsFilter{ @Override publicvoidinit(FilterConfigfilterConfig)throwsServletException{ //TODOAuto-generatedmethodstub } @Override publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain) throwsIOException,ServletException{ chain.doFilter(request,response); } @Override publicvoiddestroy(){ //TODOAuto-generatedmethodstub } }
注:经测试,@Order并不能实现过滤器排序功能,在springboot中注解的方式增加过滤器可通过修改过滤器文件名称的方式排序,如上的过滤器TestFilter1在TestFilter2前。
补充知识:SpringBoot2.1.x,集成Filter过滤器的三种方式,包含OncePerRequestFilter方式
一)Filter过滤器简介
主要作用:Filter使用户可以改变一个request和修改一个response,它能够在一个request到达servlet之前预处理request,也可以在response离开servlet时处理response。例如收集数据和包装数据,并进行处理。
1、Filter是依赖Servlet容器的,如Tomcat。
2、Filter对所有的请求起作用,并是在sevlet之前处理。可以理解成过滤器中包含拦截器,当一个请求过来,先进行过滤器处理,再看程序是否受理该请求。过滤器执行完后,程序中的拦截器再进行处理。
3、Filter只能处理HttpServletRequest和HttpServletResponse,底层是基于回调函数。
二)SpringBoot集成Filter过滤器
第一步:先创建一个maven项目,引入springboot的jar
4.0.0 com.oysept springboot_filter 0.0.1-SNAPSHOT jar org.springframework.boot spring-boot-starter-parent 2.1.4.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin com.oysept.FilterApplication org.apache.tomcat.maven tomcat7-maven-plugin
添加一个application.yml配置文件,指定一个端口
server:
port:8080
创建一个Demo测试接口
packagecom.oysept.controller; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RequestMethod; importorg.springframework.web.bind.annotation.RequestParam; importorg.springframework.web.bind.annotation.RestController; /** *DemoController *@authorouyangjun */ @RestController publicclassDemoController{ //带参GET请求:http://localhost:8080/demo/get/param?param=111222333444 @RequestMapping(value="/demo/get/param",method=RequestMethod.GET) publicStringgetParam(@RequestParam(value="param")Stringparam){ System.out.println("=====>进入DemoController/demo/get/param"); return"/demo/get/param,"+param; } }
第二步:使用@WebFilter注解方式,实现Filter过滤器
当使用@WebFilter、@WebServlet、@WebListener等注解时,需要在springboot启动类中启用@ServletComponentScan注解指定扫描包。
packagecom.oysept.filter; importjava.io.IOException; importjava.util.Enumeration; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletContext; importjavax.servlet.ServletException; importjavax.servlet.annotation.WebFilter; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.springframework.core.env.Environment; importorg.springframework.web.filter.OncePerRequestFilter; /** *过滤器,过滤所有地址 *方式一:使用@WebFilter、@WebServlet、@WebListener等注解时,需要在springboot启动类中启用@ServletComponentScan注解指定扫描包 *方式二:结合@WebFilter和@Component注解一起使用,但可能会同时注入两个bean,可能会报错,可在application.yml配置中启用同名Bean覆盖:spring.main.allow-bean-definition-overriding=true *@authorouyangjun */ @WebFilter(value="/*",filterName="oauthFilter") publicclassOAuthFilterextendsOncePerRequestFilter{ @Override protectedvoiddoFilterInternal(HttpServletRequestrequest,HttpServletResponseresponse,FilterChainfilterChain) throwsServletException,IOException{ System.out.println("====>进入OAuthFilterdoFilterInternal过滤器===="); System.out.println("请求地址:"+request.getRequestURL()); System.out.println("GET请求参数:"); Enumerationparameters=request.getParameterNames(); StringparameterName=""; while(parameters.hasMoreElements()){ parameterName=parameters.nextElement(); System.out.println("参数名称:"+parameterName+",值:"+request.getParameter(parameterName)); } //工具类 //FilterConfigfilterConfig=super.getFilterConfig(); //ServletContextservletContext=super.getServletContext(); //Environmentenvironment=super.getEnvironment(); System.out.println("====>结束OAuthFilterdoFilterInternal过滤器===="); filterChain.doFilter(request,response); } }
第三步:使用@Component注解方式,实现Filter过滤器
packagecom.oysept.filter; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.springframework.stereotype.Component; /** *过滤器通过@Component注解注册 *@authorouyangjun */ @Component publicclassPathFilterimplementsFilter{ @Override publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain) throwsIOException,ServletException{ //转换 HttpServletRequestrequest=(HttpServletRequest)servletRequest; HttpServletResponseresponse=(HttpServletResponse)servletResponse; System.out.println("====>进入PathFilterdoFilter过滤器===="); System.out.println("====>结束PathFilterdoFilter过滤器===="); filterChain.doFilter(request,response); } }
第四步:通过@Bean注解方式,实现Filter过滤器
@Configuration注解:相当于spring中的
@Bean注解:相当于spring中
packagecom.oysept.config; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.springframework.boot.web.servlet.FilterRegistrationBean; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; /** *@Configuration注解:相当于spring中的标签 *@Bean注解:相当于spring中 标签 *@authorouyangjun */ @Configuration publicclassMyFilterConfig{ @Bean publicFilterRegistrationBean testFilterRegistration(){ FilterRegistrationBean registration=newFilterRegistrationBean<>(); registration.setFilter(newMyFilter()); registration.addUrlPatterns("/*");//配置过滤路径 registration.addInitParameter("paramName","paramValue");//添加初始值 registration.setName("myFilter");//设置filter名称 registration.setOrder(1);//请求中过滤器执行的先后顺序,值越小越先执行 returnregistration; } //实现一个过滤器 publicclassMyFilterimplementsFilter{ @Override publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain) throwsIOException,ServletException{ //转换 HttpServletRequestrequest=(HttpServletRequest)servletRequest; HttpServletResponseresponse=(HttpServletResponse)servletResponse; System.out.println("====>进入MyFilterdoFilter过滤器===="); System.out.println("====>结束MyFilterdoFilter过滤器===="); filterChain.doFilter(request,response); } } }
第五步:创建一个SpringBoot启动类,并通过@ServletComponentScan注解指定扫描的Filter实现类
packagecom.oysept; importorg.springframework.boot.autoconfigure.SpringBootApplication; importorg.springframework.boot.builder.SpringApplicationBuilder; importorg.springframework.boot.web.servlet.ServletComponentScan; /** *@ServletComponentScan注解不指定扫描包时,默认扫描当前包和子包 *@authorouyangjun */ @SpringBootApplication @ServletComponentScan(basePackages="com.oysept.filter") publicclassFilterApplication{ publicstaticvoidmain(String[]args){ newSpringApplicationBuilder(FilterApplication.class).run(args); } }
启动main方法,在浏览器输入地址:http://localhost:8080/demo/get/param?param=111222333444
在控制台查看打印日志:
项目结构图:
以上这篇解决springboot中配置过滤器以及可能出现的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。