• web项目继承ServletContainerInitializer进行访问HttpServlet(WebServlet)


    java使用web项目不需要加web.xml

    配置javax.servlet.ServletContainerInitializer

    1、在src目录创建META-INF,META-INF目录下创建services,在services目录下创建javax.servlet.ServletContainerInitializer文件

    2、配置引用接口ServletContainerInitializer

    创建类MyWebConfig
    package myWeb;
    
    import javax.servlet.ServletContainerInitializer;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.HandlesTypes;
    import java.util.Set;
    
    @HandlesTypes(value = SpringWeb.class)
    public class MyWebConfig implements ServletContainerInitializer {
        @Override
        public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
            System.out.println("sadsa");
            for (Class<?> aClass : set) {
                SpringWeb o = null;
                try {
                    o = (SpringWeb) aClass.newInstance();
                    o.config();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    View Code

    3、接口

    package myWeb;
    
    public interface SpringWeb {
        void config();
    }

    4、实现类

    package myWeb;
    
    public class SpringWebInitializer implements SpringWeb {
        //配置
        @Override
        public void config() {
            System.out.println("初始化");
        }
    }

    5、访问地址HttpServlet

    @WebServlet("/asd")
    public class ServletWeb extends HttpServlet {
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("Asdds");
        }
    }

    6、tomcat测试:

     

    demo:https://github.com/weibanggang/serviceWebConfig

  • 相关阅读:
    docker 入门(docker 镜像 、容器、仓库)
    windows 安装 docker
    关于go mod 的使用和goland 配置 go mod
    mac 安装docker
    vm 将宿主机文件夹 映射至 虚拟机
    centos 关于yum无法使用
    mac 安装 swoole 可能会出现的错误
    BZOJ3378:[USACO]MooFest 狂欢节(树状数组)
    BZOJ3110:[ZJOI2013]K大数查询(整体二分)
    BZOJ4170:极光(CDQ分治)
  • 原文地址:https://www.cnblogs.com/weibanggang/p/10157030.html
Copyright © 2020-2023  润新知