第五篇:Spring Boot整合filter
原创
©著作权归作者所有:来自51CTO博客作者gblfy的原创作品,请联系作者获取转载授权,否则将追究法律责任
一、Springboot整合Servlet
第一种方案:通过注解扫描完成filter组建的注册
- 1、编写自定义filter(FirstFilter)
//urlPattern是一个数组可以添加多个
//@WebFilter(filterName = "FirstFilter",urlPatterns = {"*.do","*.jsp"})
@WebFilter(filterName = "FirstFilter", urlPatterns = {"/first"})
public class FirstFilter 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("进入filter");
// //放行
chain.doFilter(request, response);
System.out.println("离开filter");
}
@Override
public void destroy() {
}
}
@WebServlet(name = "FirstServlet",urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("FirstServlet启动........");
}
}
@SpringBootApplication
@ServletComponentScan
//在springboot启动时会扫描@Webfilter注解和@webFilter注解,并将该类实例化
public class SpringBootChapter1Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootChapter1Application.class, args);
}
}
第二种方案:通过方法完成filter组件注册
public class SecondFilter 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("进入SecondFilter");
//放行
chain.doFilter(request, response);
System.out.println("离开SecondFilter");
}
@Override
public void destroy() {
}
}
public class SecondServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("SecondServlet启动........");
}
}
/**
* @author gblfy
* @ClassNme AppFilter2
* @Description springboot整合filter方式2
* @Date 2019/2/20 13:45
* @version1.0
*/
@SpringBootApplication
public class SpringbootFilterApplication2 {
public static void main(String[] args) {
SpringApplication.run(SpringbootFilterApplication2.class, args);
}
// 注册servlet
@Bean
public ServletRegistrationBean getServletRegistrationBean() {
ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/second");
return bean;
}
// 注册filter
@Bean
public FilterRegistrationBean getFilterRegistrationBean() {
FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
// bean.addUrlPatterns(new String[]{"*.do","*.jsp"});
bean.addUrlPatterns("/second");
return bean;
}
}
本文源码下载:
github地址:
https://github.com/gb-heima/Spring-Boot-Actual-Combat/tree/master/parent/spring-boot-chapter-5