Spring Boot-6 配置Filter

  Spring Boot配置Filter有两种方式。下面分别来介绍。

  定义一个类实现Filter接口

  重写3个方法。初始化init,执行doFilter,销毁destroy。


public class MyFilter1 implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}

  在启动类上添加注解:@ServletComponentScan

 Spring Boot官网是这么介绍@ServletComponentScan:

  Scanning for Servlets, Filters, and listeners
When using an embedded container, automatic registration of @WebServlet, @WebFilter, and @WebListener annotated classes can be enabled using @ServletComponentScan

  翻译成中文:

  Scanning for Servlets, Filters, and listeners
When using an embedded container, automatic registration of @WebServlet, @WebFilter, and @WebListener annotated classes can be enabled using @ServletComponentScan

方式一:

  在自定义MyFilter1类上使用注解@WebFilter,这样就配置好了。

 @WebFilter常用属性

属性类型是否必需说明
asyncSupportedboolean指定Filter是否支持异步模式
dispatcherTypesDispatcherType[]指定Filter对哪种方式的请求进行过滤。
支持的属性:ASYNC、ERROR、FORWARD、INCLUDE、REQUEST;
默认过滤所有方式的请求
filterNameStringFilter名称
initParamsWebInitParam[]配置参数
displayNameStringFilter显示名
servletNamesString[]指定对哪些Servlet进行过滤
urlPatterns/valueString[]两个属性作用相同,指定拦截的路径

  我们可以使用filterName指定过滤器的名字。使用value指定过滤的规则。

 

方式二:

  使用配置类注册自定义的Filter.不使用注解@WebFilter

  自定义过滤器配置类:

  使用注解@Configuration

@Configuration
public class FilterConfig {

	@Bean
	public FilterRegistrationBean someFilterRegistration() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(myfilter());
		//配置过滤规则
		registration.addUrlPatterns("/*");
		registration.addInitParameter("paramName", "paramValue");
		//设置过滤器名字
		registration.setName("myfilter");
		registration.setOrder(2);
		return registration;
	}

	@Bean(name = "myfilter")
	public Filter myfilter() {
		return new MyFilter1();
	}

}

  至此方式二也完成了。

多Filter顺序

  在方式一中可以在自定义Filter的类上添加注解@Order。值为整形,越小优先级越高。

  在方式二中可以在注册自定义Filter中设置,使用setOrder()方法。

设置忽略的url

  在自定义的Filter类中。定义一个set集合,元素为不必过滤的url。然后在doFilter中判断。代码如下

  

public class TokenFilter implements Filter {

	private static final Set<String> ALLOWED_PATHS = Collections
			.unmodifiableSet(new HashSet<>(Arrays.asList("/user/getServerRSAPublicKey", "/user/registerForLawyer",
					"/user/login", "/user/getVerificationCode", "/user/wechatLogin")));

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");
		boolean allowedPath = ALLOWED_PATHS.contains(path);
		if (allowedPath) {
			filterChain.doFilter(req, res);
		} else {
			//添加需过滤的url的逻辑
			filterChain.doFilter(request, res);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}

 

 

要使用 `druid-spring-boot-starter`,你需要在你的 Maven 项目中添加以下依赖: ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> ``` 然后,你可以在你的 `application.properties` 或 `application.yml` 文件中配置 `druid` 数据源。以下是一个示例: ```yaml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db_name?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC username: root password: yourpassword type: com.alibaba.druid.pool.DruidDataSource # 下面是 druid 配置 # 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 initial-size: 5 # 最小连接池数量 min-idle: 5 # 最大连接池数量 max-active: 20 # 获取连接时最大等待时间,单位毫秒 max-wait: 60000 # 是否开启 PSCache pool-prepared-statements: true # 指定每个连接上 PSCache 的大小 max-pool-prepared-statement-per-connection-size: 20 # 打开removeAbandoned功能 remove-abandoned: true # 180秒,也就是3分钟 remove-abandoned-timeout: 180 # 关闭abanded连接时输出错误日志 log-abandoned: true # 监控配置 filter: # 开启监控统计功能 stat: enabled: true # 是否打印 SQL 语句 log-slow-sql: true # 慢 SQL 记录时间阈值,单位毫秒 slow-sql-millis: 5000 # 配置监控统计拦截的 URI,多个用逗号隔开 web-stat-filter: exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" # 配置 Druid 的 StatViewServlet stat-view-servlet: url-pattern: /druid/* # IP 白名单 allow: 127.0.0.1 # IP 黑名单(共同存在时,deny优先于allow) deny: 192.168.0.1 # 登录用户名 login-username: admin # 登录密码 login-password: admin123 ``` 以上是一个基本的 `druid` 配置,你可以根据自己的实际需求进行调整。配置完成后,你就可以在代码中使用 `DataSource` 了,例如: ```java @Autowired DataSource dataSource; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值