xml方式配置Java过滤器
在传统的Java EE应用中,web.xml是一个用于配置Servlet、Filter等的部署描述文件。如果你不使用注解而是希望通过web.xml来配置过滤器,你可以按照以下步骤进行操作。
xml方式配置Java过滤器
创建一个实现了Filter接口的类
import javax.servlet.*;
import java.io.IOException;
public class CustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 初始化代码
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 在请求前执行的代码
System.out.println("CustomFilter is invoked.");
// 执行过滤器逻辑,比如安全检查等
// 继续执行过滤链
chain.doFilter(request, response);
// 在请求后执行的代码
}
@Override
public void destroy() {
// 销毁时的代码
}
}
配置web.xml
在web.xml文件中添加过滤器的配置。你需要指定过滤器的名称、要执行的过滤器类以及它要过滤的URL模式。
请确保将<filter-class>标签内的值替换为你的过滤器类的完全限定名(包括包名)。
<web-app xmlns="<http://xmlns.jcp.org/xml/ns/javaee>"
xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instance>"
xsi:schemaLocation="<http://xmlns.jcp.org/xml/ns/javaee>
<http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd>"
version="4.0">
<filter>
<filter-name>CustomFilter</filter-name>
<filter-class>com.example.CustomFilter</filter-class>
<!-- 这里可以添加初始化参数 -->
</filter>
<filter-mapping>
<filter-name>CustomFilter</filter-name>
<url-pattern>/*</url-pattern> <!-- 这里指定过滤器要过滤的路径 -->
</filter-mapping>
<!-- 其他配置... -->
</web-app>
自定义排除
在web.xml中配置过滤器时,你可以通过指定不同的<url-pattern>来控制哪些请求被过滤器处理。
如果你想要放行某些请求,即不让过滤器处理,你可以采取的策略是将这些请求的URL模式排除在过滤器的URL模式之外。
由于web.xml本身并不提供直接的排除语法,你需要明确地定义你希望过滤器处理的URL模式。
任何不匹配这些模式的请求都会自然地被放行。
例如,假设你想要过滤所有的请求,但要放行/public/*路径下的请求,你可以这样配置web.xml
步骤一:
<filter>
<filter-name>CustomFilter</filter-name>
<filter-class>com.example.CustomFilter</filter-class>
</filter>
<!-- 为CustomFilter配置映射,拦截所有请求 -->
<filter-mapping>
<filter-name>CustomFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 其他配置 -->
步骤二:
在上面的配置中,所有的请求都会被CustomFilter拦截。如果你想放行/public/*,你将需要在你的CustomFilter的doFilter方法中添加逻辑来检查请求的URL。
这段代码将会检查每个请求的URI,如果它以/public/开头,过滤器将直接放行该请求,否则将应用过滤器的逻辑。
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
// 放行/public/*下的请求
if (path.startsWith("/public/")) {
chain.doFilter(request, response); // 直接传递到下一个元素(可能是另一个过滤器或目标资源)
return;
}
// 以下是对于非/public/*请求的过滤逻辑
System.out.println("CustomFilter is invoked.");
// 执行过滤器逻辑...
// 继续执行过滤链
chain.doFilter(request, response);
}
注意事项
从Servlet 3.0规范开始,可以使用注解来配置过滤器。
如果同时使用注解和web.xml进行配置,那么web.xml的配置将会覆盖注解的配置。
当使用web.xml配置时,你不能使用注解中的元数据,如注解属性等,因为这些是通过注解处理的。所以你的过滤器逻辑需要独立于注解属性。