springboot-03 servlet三大组件

springboot注册Servlet三大组件【Servlet、Filter、Listener】

SpringBoot默认以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,不需要进行xml文件配置。

注册三大组件用以下方式

  • SERVLET

    一般情况下显示需要写自己的servlet去继承HttpServlet,重写doPost和doGet方法。

        //处理get请求
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doPost(req,resp);
        }
        //处理post请求
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.getWriter().write("Hello MyServlet");
        }
    

    接下来在配置类中进行注册。

//注册三大组件
@Bean
public ServletRegistrationBean myServlet(){
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
   //启动顺序
        registrationBean.setLoadOnStartup(1);
    return registrationBean;
}

  • Filter

    需要自定义Filter,实现Filter接口 (三个接口)

    Init,初始化
    doFilter,过滤
    destroy,销毁
    chain.doFilter,放行请求

    接下来在配置中及进行注册

FilterRegistrationBean

@Bean
public FilterRegistrationBean myFilter(){
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new MyFilter());
    registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
    return registrationBean;
}
  • Listener

    contextInitialized,初始化方法,Web项目启动

    contextDestroyed,销毁方法,Web项目销毁(直接exit时使用)

ServletListenerRegistrationBean

@Bean
public ServletListenerRegistrationBean myListener(){
    ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
    return registrationBean;
}

关于三大组件:就是所有的代码几乎是不可变的,需要写的代码很多,并不适合spring。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值