servlet脏话过滤器简单案例
时间: 2023-12-08 20:05:20 浏览: 102
过滤器与监听器-Servlet过滤器与监听器
以下是一个简单的Servlet脏话过滤器的示例:
```java
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(filterName = "DirtyWordsFilter", urlPatterns = {"/*"})
public class DirtyWordsFilter implements Filter {
private static final String[] DIRTY_WORDS = {"xxx", "yyy", "zzz"};
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String requestURI = httpRequest.getRequestURI();
if (requestURI != null && !requestURI.endsWith(".css") && !requestURI.endsWith(".js")) { // 排除静态资源
String message = httpRequest.getParameter("message");
if (message != null) {
for (String dirtyWord : DIRTY_WORDS) {
message = message.replaceAll(dirtyWord, "***");
}
request.setAttribute("message", message); // 将过滤后的消息存入request中
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
```
该过滤器会拦截所有请求,并排除静态资源。如果请求中包含名为"message"的参数,该过滤器会检查该参数中是否包含脏话,如果包含,则将其替换为"***",并将过滤后的消息存入request中。开发人员可以在servlet中获取过滤后的消息并进行处理。
阅读全文