WebServlet原生组件注入

1、使用Servlet API

@ServletComponentScan(basePackages = "com.atguigu.admin") :指定原生Servlet组件都放在那里

@WebServlet(urlPatterns = "/my"):效果:直接响应,没有经过Spring的拦截器? 因为匹配不一样 等会细说

@WebFilter(urlPatterns={"/css/*","/images/*"}) 过滤器

@WebListener监听器

 

2、使用RegistrationBean

ServletRegistrationBeanFilterRegistrationBean, and ServletListenerRegistrationBean

这些都是以注册Bean的方式

 

复制代码
@Configuration
public class MyRegistConfig {

    @Bean
    public ServletRegistrationBean myServlet(){
        MyServlet myServlet = new MyServlet(); //原生的Servlet

        return new ServletRegistrationBean(myServlet,"/my","/my02");//Servlet注册Bean  第一次参数就是原生servlet  第二个参数就是请求路径  感觉都没注解+扫包方便
    }


    @Bean
    public FilterRegistrationBean myFilter(){

        MyFilter myFilter = new MyFilter();//原生servlet的过滤
//        return new FilterRegistrationBean(myFilter,myServlet()); 第一种方式 第一个参数过滤器,第二个参数目标过滤  这种方式只能拦截myservlet中的路径
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));//这种方式 就是指定的拦截 请求路径
        return filterRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener(){
        MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
        return new ServletListenerRegistrationBean(mySwervletContextListener);//因为监听器是程序启动时就运行的,所以不需要额外添加其他参数
    }
}
复制代码

 

posted @   咖喱给给啊  阅读(21)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示