@WebFilter是Java Servlet规范中的一个注解,用于标识一个类为过滤器(Filter)。过滤器用于在请求进入Servlet之前或响应返回给客户端之前,对请求和响应进行预处理或后处理。
使用@WebFilter注解,可以将一个类声明为过滤器,并指定要过滤的URL模式、过滤器的顺序等。
以下是一个示例,展示如何使用@WebFilter注解创建一个过滤器:
第一步:创建一个过滤器,代码如下
@WebFilter(urlPatterns = "/api/*")
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 过滤器初始化操作
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 过滤器处理请求和响应的逻辑
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
// 过滤器销毁操作
}
}
第二步:在主应用程序类上添加
@ServletComponentScan
注解
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class ErweimaApplication {
public static void main(String[] args) {
SpringApplication.run(ErweimaApplication.class, args);
}
}
在上述示例中,我们使用@WebFilter注解将MyFilter类声明为一个过滤器,并指定了要过滤的URL模式为"/api/*",即以"/api/"开头的所有请求都会经过该过滤器。
我们可以根据需要过滤的需求,在doFilter方法中编写自定义的过滤逻辑来处理请求和响应。
下面代码是对请求拦截和放行做的一个简单处理
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 过滤逻辑
boolean isFilter = true;
// 放行
if(isFilter){
filterChain.doFilter(servletRequest,servletResponse);
}
// 拦截 直接结束响应
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("application/json; charset=utf-8");
servletResponse.getWriter().append(
new JSONObject()
.fluentPut("msg", "非法请求,请尽快中止非法请求,否则将会记录危险请求方信息!")
.fluentPut("success", "false")
.fluentPut("code", "500")
.toString()
);
}
拦截后响应结果如下图