spring-boot实现增加自定义filter(新)
程序员文章站
2024-02-24 22:42:52
前言
传统的javaee增加filter是在web.xml中配置,如以下代码:
te...
前言
传统的javaee增加filter是在web.xml中配置,如以下代码:
<filter> <filter-name>testfilter</filter-name> <filter-class>com.cppba.filter.testfilter</filter-class> </filter> <filter-mapping> <filter-name>testfilter</filter-name> <url-pattern>/*</url-pattern> <init-param> <param-name>paramname</param-name> <param-value>paramvalue</param-value> </init-param> </filter-mapping>
然而spring-boot中很明显不能这样实现,那怎么办呢?看完下面的教程,答案自然知道了。
老方法(新方法请直接下拉)
1.创建自定义filter
package com.cppba.filter; import javax.servlet.*; import java.io.ioexception; public class testfilter 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("testfilter"); } @override public void destroy() { } }
2.在applicationconfiguration.java中增加一个@bean
@bean public filterregistrationbean testfilterregistration() { filterregistrationbean registration = new filterregistrationbean(); registration.setfilter(new testfilter()); registration.addurlpatterns("/*"); registration.addinitparameter("paramname", "paramvalue"); registration.setname("testfilter"); registration.setorder(1); return registration; }
3.启动项目
你会看到控制台打印如下代码:
4.访问项目
最后我们访问以下http://127.0.0.1:8080/test
如果你看到控制台打印出:testfilter
恭喜你,配置成功!
2017-04-20 最新spring-boot增加filter方法
首先定义一个filter
@order(1) //重点 @webfilter(filtername = "testfilter1", urlpatterns = "/*") public class testfilterfirst 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("testfilter1"); filterchain.dofilter(servletrequest,servletresponse); } @override public void destroy() { } }
比较核心的代码是自定义类上面加上@webfilter,其中@order注解表示执行过滤顺序,值越小,越先执行
我们在spring-boot的入口处加上如下注解@servletcomponentscan:
@springbootapplication(scanbasepackages = "com.cppba") //重点 @servletcomponentscan public class application { public static void main(string[] args) throws unknownhostexception { springapplication app = new springapplication(application.class); environment environment = app.run(args).getenvironment(); } }
这种方法效果和上面版本一样,但是用起来更加方便!以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 使用Python对SQLite数据库操作
推荐阅读