Servlet3.0之七:@WebFilter申明该类为过滤器
Servlet3.0作为J2EE 6规范一部分,并随J2EE6一起发布,@WebFilter是过滤器注解,是Servlet3.0的新特性,不需要在web.xml进行配置,简化了配置。
一、Filter介绍
二、@WebFilter用法
在servlet3.0以后,我们可以不用再web.xml里面配置Filter,只需要加上@WebFilter注解就可以实现。
下面是@WebFilter的属性列表。
Name |
Type |
Required |
Description |
filterName |
String |
Optional |
Name of the filter. |
value or urlPatterns |
String[] |
Required |
Specify one or more URL patterns to which the filter applies. Either of attribute can be used, but not both. |
dispatcherTypes |
DispatcherType[] |
Optional |
Specify types of dispatcher to which the filter applies. Default isjavax.servlet.DispatcherType.REQUEST |
servletNames |
String[] |
Optional |
Specify names of servlets to which the filter applies. |
displayName |
String |
Optional |
Display name of the filter. |
description |
String |
Optional |
Description of the filter. |
asyncSupported |
boolean |
Optional |
Specify whether the filter supports asynchronous operation mode. Default is false. |
initParams |
WebInitParam[] |
Optional |
Specify one or more initialization parameters of the filter. Each parameter is specified by@WebInitParamannotation type. |
smallIcon |
String |
Optional |
Specify name of the small icon of the filter. |
largeIcon |
String |
Optional |
Specify name of the large icon of the filter. |
示例:
package com.dxz.demo.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; @WebFilter(filterName = "oneFilter", //不指定name的情况下,name默认值为类全路径,即com.dxz.demo.filter.oneFilter urlPatterns="/filter/*", description="注解声明filter", initParams={//以下都是druid数据源状态监控的参数 @WebInitParam(name="allow",value=""),// IP白名单 (没有配置或者为空,则允许所有访问) @WebInitParam(name="deny",value=""),// IP黑名单 (存在共同时,deny优先于allow) @WebInitParam(name="loginUsername",value="dev"),// 用户名 @WebInitParam(name="loginPassword",value="123456"),// 密码 @WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能 }) public class OneFilter implements Filter { @Override public void init(FilterConfig config) throws ServletException { System.out.println("OneFilter init()"); System.out.println(config.getInitParameter("loginUsername")); System.out.println(config.getInitParameter("loginPassword")); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("OneFilter doFilter()"); chain.doFilter(request, response); } @Override public void destroy() { } }
结果:
注意:
1、Filter类使用@WebFilter注解;
2、Spring boot的启动类需要增加@ServletComponentScan用于扫描加载Filter类;