一、filter-mapping元素
filter-mapping元素用于将filter和servlet或jsp进行关联,它可以指定一个Filter对哪些URL请求进行拦截,并对该Filter在web.xml中的配置进行相应的映射。filter-mapping元素有以下几种配置方式:
1.1、通过filter-name配置
<filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/myUrl</url-pattern> </filter-mapping>
通过filter-name指定Filter在web.xml中的名称,url-pattern指定要拦截的URL请求,此时,myFilter会拦截到所有myUrl的请求。
1.2、通过servlet-name配置
<filter-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/myUrl</url-pattern> </filter-mapping>
通过servlet-name指定要拦截的Servlet,在请求到达该Servlet之前,myFilter会对请求进行拦截。
1.3、通过dispatchers配置
<filter-mapping> <filter-name>myFilter</filter-name> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping>
通过dispatchers指定拦截类型,dispatcher有以下几种取值:
- REQUEST:对所有请求进行拦截
- FORWARD:对转发请求进行拦截
- INCLUDE:对包含其他文件的请求进行拦截
- ERROR:对错误处理请求进行拦截
- ASYNC:对异步请求进行拦截
二、filter-mapping url-pattern
url-pattern用于指定过滤器拦截的URL模式,它支持如下几种模式:
2.1、精确匹配
<filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/myUrl</url-pattern> </filter-mapping>
精确匹配指定的URL请求,只有当URL请求的完全匹配指定的URL模式时,Filter才会进行过滤。
2.2、目录匹配
<filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/myDir/*</url-pattern> </filter-mapping>
目录匹配指定的URL请求,只要URL模式匹配指定目录下的所有文件,Filter就会进行过滤。这里的“*”表示只匹配该目录下的文件,不包含子目录。
2.3、扩展名匹配
<filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>*.html</url-pattern> </filter-mapping>
扩展名匹配指定的URL请求,只要URL的扩展名匹配指定的字符串,Filter就会进行过滤。
2.4、默认匹配
<filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/</url-pattern> </filter-mapping>
默认匹配指定的URL请求,仅当没有其它匹配URL模式时,Filter才会进行过滤。
三、filter-mapping排除
排除指的是某些URL请求不被Filter拦截,可以通过以下方式进行排除:
3.1、通过url-pattern排除
<filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/myUrl/*</url-pattern> <url-pattern>!*.jsp</url-pattern> </filter-mapping>
通过url-pattern指定要排除哪些URL请求,只有URL模式不匹配排除的URL模式时,Filter才会进行过滤。
3.2、通过dispatcher排除
<filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/myUrl</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>!ASYNC</dispatcher> </filter-mapping>
通过dispatcher指定要排除哪些拦截类型的请求,只有请求类型不包含排除类型时,Filter才会进行过滤。
示例代码:
<filter> <filter-name>myFilter</filter-name> <filter-class>com.example.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>myFilter</filter-name> <url-pattern>/myUrl/*</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/248072.html