【Spring Boot】过滤敏感词的两种实现
在Spring Boot中,可以通过实现Filter
接口来过滤敏感词汇。以下是两种实现方式的示例代码:
方式一:直接在Filter中进行过滤
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class SensitiveWordsFilter implements Filter {
private List<String> sensitiveWords = Arrays.asList("敏感", "词汇");
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
String requestUri = httpServletRequest.getRequestURI();
String queryString = httpServletRequest.getQueryString(); // 可以用来过滤URL参数
// 这里可以添加对requestUri和queryString的敏感词过滤逻辑
chain.doFilter(request, response);
}
// 省略其他方法...
}
方式二:使用AOP(面向切面编程)进行过滤
首先,添加Spring AOP依赖到pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
然后,创建一个Aspect类来处理敏感词过滤:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Aspect
@Component
public class SensitiveWordsAspect {
private List<String> sensitiveWords = Arrays.asList("敏感", "词汇");
@Before("execution(* com.yourpackage..*Controller.*(..))") // 根据实际情况配置切点
public void checkSensitiveWords(JoinPoint joinPoint) {
// 这里添加对传入参数的敏感词过滤逻辑
}
}
在这两种方式中,你需要自行实现对应的敏感词过滤逻辑。通常情况下,敏感词过滤可以使用正则表达式或者字符串匹配的方式来实现。记得在application.properties
或application.yml
中添加对应的配置,以便启用这些Filter。
评论已关闭