原生注解方式注入web原生组件
- 使用原生注解注入servlet组件:@WebServlet处理请求路由,+主配置类中标注@ServletComponentScan扫描原生注解所在的路径
@WebServlet(urlPatterns = "/my")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("66666");
}
}
@MapperScan("com.atguigu.admin.mapper")
@ServletComponentScan(basePackages = "com.atguigu.admin")
@SpringBootApplication(exclude = RedisAutoConfiguration.class)
public class Boot05WebAdminApplication {
public static void main(String[] args) {
SpringApplication.run(Boot05WebAdminApplication.class, args);
}
}
``
- 使用原生注解注入filter组件:@WebFilter + @ServletComponentScan
@Slf4j
@WebFilter(urlPatterns={"/css/","/images/"}) // 表示拦截该路径下的静态资源
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("MyFilter初始化完成");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("MyFilter工作"); // 拦截后进行逻辑处理
chain.doFilter(request,response); // 最后放行,放行后可访问
}
@Override
public void destroy() {
log.info("MyFilter销毁");
}
}
- 使用原生组件注入listener组件:@WebListener + @ServletComponentScan
@Slf4j
@WebListener
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.info("MySwervletContextListener监听到项目初始化完成");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.info("MySwervletContextListener监听到项目销毁");
}
}