springboot 注册三大组件(servlet,Filter,Listener)

注册servlet

创建一个自定义servlet

public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getOutputStream().println("hahaha");
    }
}

在配置类中注册servlet

@Configuration
public class MyMvcConfig   {
    @Bean
    public ServletRegistrationBean addservlet()
    {     // 创建Servlet注册Bean
        ServletRegistrationBean<MyServlet> servletServletRegistrationBean=new ServletRegistrationBean<MyServlet>();
        // 注册Servlet
        servletServletRegistrationBean.setServlet(new MyServlet());
        // 设置Servlet名称
        servletServletRegistrationBean.setName("second_servlet");
        // 设置Servlet访问地址
        servletServletRegistrationBean.addUrlMappings("/hello");
        // 设置加载参数
        servletServletRegistrationBean.setLoadOnStartup(1);
        return  servletServletRegistrationBean;
    }

注册Filter

创建一个自定义Filter

public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("qwer");
        filterChain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() { }
}

配置类注册Filter

    @Bean
    public FilterRegistrationBean addFilter()
    {
        FilterRegistrationBean<MyFilter> filterFilterRegistrationBean=new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setFilter(new MyFilter());
        //拦截的请求
        filterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/haha"));
        return  filterFilterRegistrationBean;
    }

注册Listener

创建一个自定义Listener

public class MyListener implements ServletRequestListener {
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("项目销毁");
    }
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("项目创建");
    }
}

配置类注册Listener

    @Bean
    public ServletListenerRegistrationBean addListener()
    {
     ServletListenerRegistrationBean<MyListener> servletListenerRegistrationBean=new ServletListenerRegistrationBean<>();
     servletListenerRegistrationBean.setListener(new MyListener());
     return servletListenerRegistrationBean;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值