一、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() {
}
}
  • 2、创建servlet(测试用)
@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启动........");
}
}
  • 3、编写一个启动类,并在启动类上添加注解
@SpringBootApplication
@ServletComponentScan
//在springboot启动时会扫描@Webfilter注解和@webFilter注解,并将该类实例化
public class SpringBootChapter1Application {

public static void main(String[] args) {
SpringApplication.run(SpringBootChapter1Application.class, args);
}

}

第二种方案:通过方法完成filter组件注册

  • 1、编写一个自定义的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() {
}
}
  • 2、创建一个servlet(测试用)
public class SecondServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("SecondServlet启动........");
}
}
  • 3、创建一个启动类
/**
* @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​