@WebFilter(urlPatterns = "/filter")
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("进入过滤器");
chain.doFilter(request,response);
}
}
@SpringBootApplication
@ServletComponentScan
public class Ch07SpringbootFilterApplication {
public static void main(String[] args) {
SpringApplication.run(Ch07SpringbootFilterApplication.class, args);
}
}
需要实现Filter接口并且重写doFilter方法
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("进入使用配置器类的过滤器");
chain.doFilter(request,response);
}
}
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean myFilterRegistrationBean(){
FilterRegistrationBean frb = new FilterRegistrationBean(new MyFilter());
//添加要过滤的路径
frb.addUrlPatterns("/user/filter/*");
return frb;
}
}
@Controller
@RequestMapping("/user")
public class MyController {
@RequestMapping("/filter/1")
public @ResponseBody String filter(){
return "filter";
}
@RequestMapping("/other")
public @ResponseBody String other(){
return "other";
}
}
首先测试没有添加过滤器的请求
控制台没有打印任何信息
然后测试添加了过滤器的请求
执行了在过滤器内的代码,测试成功
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/m0_60117382/article/details/121581731
内容来源于网络,如有侵权,请联系作者删除!