zoukankan      html  css  js  c++  java
  • 18. Spring Boot 、注册Servlet三大组件Servlet、Filter、Listener

    由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件

    public class MyServlet extends HttpServlet {
        
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException ,IOException {
              resp.getWriter().println("<h1>hello world</h1>");
        };
        
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    }
    public class MyFilter implements Filter{
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            System.out.println("================Hello world Filter");
            chain.doFilter(request, response);
            
        }
    }
    public class MyListener implements ServletContextListener {
        @Override
        public void contextInitialized(ServletContextEvent sce) {
            ServletContextListener.super.contextInitialized(sce);
            System.out.println("-------------MyListener inited !");
        }
        
        
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            ServletContextListener.super.contextDestroyed(sce);
            System.out.println("----------------MyListener Destroy !");
        }
        
    }
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
        //注册Servlet
        @Bean
        public ServletRegistrationBean<Servlet> myServlet(){
            return new ServletRegistrationBean<>(new MyServlet(),"/myServlet");
        }
        
        //注册Filter
        @Bean
        public FilterRegistrationBean<Filter> myFilter(){
            FilterRegistrationBean<Filter> filter = new FilterRegistrationBean<>();
            filter.setFilter(new MyFilter());
            filter.addUrlPatterns("/myServlet");
            
            FilterRegistrationBean<Filter> filter2 = new FilterRegistrationBean<>(new MyFilter(), myServlet());
            return filter2;
        }
    //注册Listener @Bean
    public ServletListenerRegistrationBean<EventListener> myListener(){ ServletListenerRegistrationBean<EventListener> listener = new ServletListenerRegistrationBean<EventListener>(new MyListener()); return listener; } }
  • 相关阅读:
    linux下用shell删除三天前或者三天内的文件
    linux在shell中获取时间
    mongodb_修改器($inc/$set/$unset/$push/$pop/upsert......)
    java List<Map> 排序问题
    linux crontab定时执行shell脚本
    MongoDB 基础命令——数据库表的增删改查——遍历操作表中的记录
    Windows7下安装MongoDB
    JavaWeb学习总结(十二)——Session
    javaweb学习总结(十一)——使用Cookie进行会话管理
    iOS10 SiriKit QQ适配详解
  • 原文地址:https://www.cnblogs.com/guchunchao/p/10025659.html
Copyright © 2011-2022 走看看