SpringBoot - 注入原生注解 Servlet,Filter,Listener

@ServletComponentScan(basePackages = “com.atguigu.admin”) 指定原生Servlet组件都放在那里
@WebServlet(urlPatterns = “/my”) 直接响应,没有经过Spring的拦截器
@WebFilter(urlPatterns={"/css/","/images/"})
@WebListener

在启动类上加@ServletComponentScan 注解

@ServletComponentScan(basePackages="com.zm.webs" ) //指定原生Servlet组件都放在那里;只要是com.zm.webs下的包里面有servlet都可以扫描到
@SpringBootApplication
public class SpringbootLearnApplication {
    public static void main(String[] args) {
        SpringApplication.run(Boot05WebAdminApplication.class, args);
    }

}

 

1.注入监听器

@Slf4j
@WebListener
public class MyServletContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("MyServletContextListener监听到项目初始化完成");
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("MyServletContextListener监听到项目销毁");
    }
}

2.注入过滤器

@Slf4j
@WebFilter(urlPatterns = {"/css/*","/images/*"}) //访问某个资源下的所有文件时 /**是spring的写法 /*是servlet的写法
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("MyFilter初始化完成");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("MyFilter工作");
        filterChain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() {
        log.info("MyFilter销毁");
    }
}

3.注入Servlet

@WebServlet(urlPatterns = "/my")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("Hello,servlet");
    }
}

 

posted on 2022-12-27 20:35  Mikasa-Ackerman  阅读(25)  评论(0编辑  收藏  举报

导航