org.springframework.boot.web.servlet.ServletContextInitializer Java Examples

The following examples show how to use org.springframework.boot.web.servlet.ServletContextInitializer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebAppInitializer.java    From logging-log4j-audit with Apache License 2.0 6 votes vote down vote up
@Bean
public ServletContextInitializer initializer() {
    return servletContext -> {
        LOGGER.info("Starting Audit Catalog Editor");
        servletContext.setInitParameter("applicationName", APPLICATION_NAME);
        ProfileUtil.setActiveProfile(servletContext);
        servletContext.setInitParameter("isEmbedded", "true");
        System.setProperty("applicationName", APPLICATION_NAME);
        //AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        //rootContext.setDisplayName(APPLICATION_NAME);
        //rootContext.register(WebMvcAppContext.class);
        //servletContext.addListener(new ContextLoaderListener(rootContext));

        //ServletRegistration.Dynamic restServlet = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(rootContext));
        //restServlet.setLoadOnStartup(1);
        //restServlet.addMapping("/*");
    };
}
 
Example #2
Source File: NettyEmbeddedServletContainerFactory.java    From Jinx with Apache License 2.0 6 votes vote down vote up
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
    ClassLoader parentClassLoader = resourceLoader != null ? resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader();
    Package nettyPackage = Bootstrap.class.getPackage();
    String title = nettyPackage.getImplementationTitle();
    String version = nettyPackage.getImplementationVersion();
    logger.info("Running with " + title + " " + version);
    NettyEmbeddedContext context = new NettyEmbeddedContext(nettyContainerConfig,getContextPath(),
            new URLClassLoader(new URL[]{}, parentClassLoader),
            SERVER_INFO);
    if (isRegisterDefaultServlet()) {
        logger.warn("This container does not support a default servlet");
    }
    for (ServletContextInitializer initializer : initializers) {
        try {
            initializer.onStartup(context);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
    logger.info("nettyContainerConfig :"+nettyContainerConfig.toString());
    return new NettyEmbeddedServletContainer(nettyContainerConfig, context);
}
 
Example #3
Source File: LayuiAdminStartUp.java    From layui-admin with MIT License 6 votes vote down vote up
@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    tomcat.addInitializers(new ServletContextInitializer(){
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            XmlWebApplicationContext context = new XmlWebApplicationContext();
            context.setConfigLocations(new String[]{"classpath:applicationContext-springmvc.xml"});
            DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
            ServletRegistration.Dynamic dispatcher = servletContext
                    .addServlet("dispatcher", dispatcherServlet);

            dispatcher.setLoadOnStartup(1);
            dispatcher.addMapping("/");
        }
    });
    tomcat.setContextPath("/manager");
    tomcat.addTldSkipPatterns("xercesImpl.jar","xml-apis.jar","serializer.jar");
    tomcat.setPort(port);

    return tomcat;
}
 
Example #4
Source File: PrimefacesFileUploadServletContextAutoConfiguration.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
/**
 * PrimefacesFileUploadServletContextInitializer for native uploader,
 * since {@link FileUploadFilter} suffices for commons file uploader.
 *
 * @param multipartConfigElement {@link MultipartAutoConfiguration#multipartConfigElement()}
 * @return primefaces file upload servlet context initializer
 */
@ConditionalOnExpression("'${joinfaces.primefaces.uploader}' != 'commons'")
@Bean
public ServletContextInitializer primefacesFileUploadServletContextInitializer(MultipartConfigElement multipartConfigElement) {
	return servletContext -> {
		ServletRegistration servletRegistration = servletContext.getServletRegistration(FACES_SERVLET_NAME);
		if (servletRegistration instanceof ServletRegistration.Dynamic) {
			((ServletRegistration.Dynamic) servletRegistration).setMultipartConfig(multipartConfigElement);
		}
	};
}
 
Example #5
Source File: SpringBootInitializer.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public ServletContextInitializer servletContextInitializer() {
    return servletContext -> {
        WebApplicationContext ctx = getRequiredWebApplicationContext(servletContext);
        ConfigurableEnvironment environment = ctx.getBean(ConfigurableEnvironment.class);
        SessionCookieConfig config = servletContext.getSessionCookieConfig();
        config.setHttpOnly(true);
        config.setSecure(environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_LIVE)));
        // force log initialization, then disable it
        XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING);
        XRLog.setLoggingEnabled(false);
    };
}
 
Example #6
Source File: WebContextConfiguration.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@Bean
public ServletContextInitializer servletContextInitializer() {
    return context -> context.setAttribute(
            JarScanner.class.getName(),
            new StandardJarScanner() {{
                setScanManifest(false);
            }}
    );
}
 
Example #7
Source File: MockServer.java    From funcatron with Apache License 2.0 5 votes vote down vote up
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(
        ServletContextInitializer... initializers) {
    this.container = new MockEmbeddedServletContainer(
            mergeInitializers(initializers), getPort());
    return this.container;
}
 
Example #8
Source File: ServerlessServletEmbeddedServerFactory.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Override
public void start() throws EmbeddedServletContainerException {
    for (ServletContextInitializer i : initializers) {
        try {
            if (handler.getServletContext() == null) {
                throw new EmbeddedServletContainerException("Attempting to initialize ServletEmbeddedWebServer without ServletContext in Handler", null);
            }
            i.onStartup(handler.getServletContext());
        } catch (ServletException e) {
            throw new EmbeddedServletContainerException("Could not initialize Servlets", e);
        }
    }
}
 
Example #9
Source File: ServerlessServletEmbeddedServerFactoryTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void getWebServer_callsInitializers() {
    ServerlessServletEmbeddedServerFactory factory = new ServerlessServletEmbeddedServerFactory();
    factory.getWebServer(new ServletContextInitializer() {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            if (servletContext == null) {
                fail("Null servlet context");
            }
        }
    });
}
 
Example #10
Source File: ServerlessServletEmbeddedServerFactory.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
    this.initializers = initializers;
    for (ServletContextInitializer i : initializers) {
        try {
            if (handler.getServletContext() == null) {
                throw new WebServerException("Attempting to initialize ServletEmbeddedWebServer without ServletContext in Handler", null);
            }
            i.onStartup(handler.getServletContext());
        } catch (ServletException e) {
            throw new WebServerException("Could not initialize Servlets", e);
        }
    }
    return this;
}
 
Example #11
Source File: WebContextConfiguration.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Bean
public ServletContextInitializer servletContextInitializer() {
  return servletContext -> {
    String loggingServerIP = portalConfig.cloggingUrl();
    String loggingServerPort = portalConfig.cloggingPort();
    String credisServiceUrl = portalConfig.credisServiceUrl();

    servletContext.setInitParameter("loggingServerIP",
        Strings.isNullOrEmpty(loggingServerIP) ? "" : loggingServerIP);
    servletContext.setInitParameter("loggingServerPort",
        Strings.isNullOrEmpty(loggingServerPort) ? "" : loggingServerPort);
    servletContext.setInitParameter("credisServiceUrl",
        Strings.isNullOrEmpty(credisServiceUrl) ? "" : credisServiceUrl);
  };
}
 
Example #12
Source File: EmbeddedNettyFactory.java    From spring-boot-starter-netty with GNU General Public License v3.0 5 votes vote down vote up
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... initializers) {
    ClassLoader parentClassLoader = resourceLoader != null ? resourceLoader.getClassLoader() : ClassUtils.getDefaultClassLoader();
    //Netty启动环境相关信息
    Package nettyPackage = Bootstrap.class.getPackage();
    String title = nettyPackage.getImplementationTitle();
    String version = nettyPackage.getImplementationVersion();
    log.info("Running with " + title + " " + version);
    //是否支持默认Servlet
    if (isRegisterDefaultServlet()) {
        log.warn("This container does not support a default servlet");
    }
    //上下文
    NettyContext context = new NettyContext(getContextPath(), new URLClassLoader(new URL[]{}, parentClassLoader), SERVER_INFO);
    for (ServletContextInitializer initializer : initializers) {
        try {
            initializer.onStartup(context);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    }
    //从SpringBoot配置中获取端口,如果没有则随机生成
    int port = getPort() > 0 ? getPort() : new Random().nextInt(65535 - 1024) + 1024;
    InetSocketAddress address = new InetSocketAddress(port);
    log.info("Server initialized with port: " + port);
    return new NettyContainer(address, context); //初始化容器并返回
}
 
Example #13
Source File: ZkMaxAutoConfiguration.java    From zkspringboot with Apache License 2.0 5 votes vote down vote up
@Bean
public ServletContextInitializer manualServletConfigInit() {
	return servletContext -> {
		//required to avoid duplicate installing of the CometAsyncServlet
		//startup sequence in spring boot is different to a normal servlet webapp
		servletContext.setAttribute("org.zkoss.zkmax.ui.comet.async.installed", true);
		servletContext.setAttribute("org.zkoss.zkmax.au.websocket.filter.installed", true);
	};
}
 
Example #14
Source File: NettyTcpServerFactory.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Get servlet container
 * @param initializers Initialize the
 * @return NettyTcpServer
 */
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
    ServletContext servletContext = Objects.requireNonNull(getServletContext());
    try {
        //The default servlet
        if (super.isRegisterDefaultServlet()) {
            servletContext.addServlet("default",new ServletDefaultHttpServlet())
                    .addMapping("/");
        }

        //JSP is not supported
        if(super.shouldRegisterJspServlet()){
            Jsp jsp = getJsp();
        }

        //Initialize the
        for (ServletContextInitializer initializer : super.mergeInitializers(initializers)) {
            initializer.onStartup(servletContext);
        }

        //Server port
        InetSocketAddress serverAddress = getServerSocketAddress(getAddress(),getPort());
        return new NettyTcpServer(serverAddress, properties, protocolHandlers,serverListeners,channelHandlerSupplier);
    }catch (Exception e){
        throw new IllegalStateException(e.getMessage(),e);
    }
}
 
Example #15
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
    if (host.getState() == LifecycleState.NEW) {
        super.prepareContext(host, initializers);
    } else {
        File documentRoot = getValidDocumentRoot();
        StandardContext context = new StandardContext();
        if (documentRoot != null) {
            context.setResources(new StandardRoot(context));
        }
        context.setName(getContextPath());
        context.setDisplayName(getDisplayName());
        context.setPath(getContextPath());
        File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase");
        context.setDocBase(docBase.getAbsolutePath());
        context.addLifecycleListener(new Tomcat.FixContextListener());
        context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
        resetDefaultLocaleMapping(context);
        addLocaleMappings(context);
        context.setUseRelativeRedirects(false);
        configureTldSkipPatterns(context);
        WebappLoader loader = new WebappLoader(context.getParentClassLoader());
        loader
            .setLoaderClass("com.alipay.sofa.ark.web.embed.tomcat.ArkTomcatEmbeddedWebappClassLoader");
        loader.setDelegate(true);
        context.setLoader(loader);
        if (isRegisterDefaultServlet()) {
            addDefaultServlet(context);
        }
        if (shouldRegisterJspServlet()) {
            addJspServlet(context);
            addJasperInitializer(context);
        }
        context.addLifecycleListener(new StaticResourceConfigurer(context));
        ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
        context.setParent(host);
        configureContext(context, initializersToUse);
        host.addChild(context);
    }
}
 
Example #16
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
    if (embeddedServerService == null) {
        return super.getWebServer(initializers);
    } else if (embeddedServerService.getEmbedServer() == null) {
        embeddedServerService.setEmbedServer(initEmbedTomcat());
    }
    Tomcat embedTomcat = embeddedServerService.getEmbedServer();
    prepareContext(embedTomcat.getHost(), initializers);
    return getWebServer(embedTomcat);
}
 
Example #17
Source File: SentryConfiguration.java    From zhcet-web with Apache License 2.0 4 votes vote down vote up
@Bean
public ServletContextInitializer sentryServletContextInitializer() {
    return new io.sentry.spring.SentryServletContextInitializer();
}
 
Example #18
Source File: ServletContextInitParameterPropertiesAutoConfiguration.java    From joinfaces with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnBean(ServletContextInitParameterProperties.class)
public ServletContextInitializer servletContextInitParameterInitializer(List<ServletContextInitParameterProperties> initParameterProperties) {
	return new InitParameterServletContextConfigurer(initParameterProperties);
}
 
Example #19
Source File: ExternalizedConfigurationWebApplicationBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 4 votes vote down vote up
@Bean
public ServletContextInitializer servletContextInitializer() {
    return (servletContext) ->
            servletContext.setInitParameter("web-app-name", "Externalized Configuration Web");
}
 
Example #20
Source File: MockServletWebServerFactory.java    From spring-security-oauth2-boot with Apache License 2.0 4 votes vote down vote up
public MockServletWebServer(ServletContextInitializer[] initializers, int port) {
	super(Arrays.stream(initializers).map((initializer) -> (Initializer) initializer::onStartup)
			.toArray(Initializer[]::new), port);
}
 
Example #21
Source File: ServerlessServletEmbeddedServerFactory.java    From aws-serverless-java-container with Apache License 2.0 4 votes vote down vote up
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(ServletContextInitializer... servletContextInitializers) {
    initializers = servletContextInitializers;

    return this;
}
 
Example #22
Source File: MockServletWebServerFactory.java    From spring-security-oauth2-boot with Apache License 2.0 4 votes vote down vote up
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
	this.webServer = spy(new MockServletWebServer(mergeInitializers(initializers), getPort()));
	return this.webServer;
}
 
Example #23
Source File: ServerlessServletEmbeddedServerFactory.java    From aws-serverless-java-container with Apache License 2.0 4 votes vote down vote up
ServletContextInitializer[] getInitializers() {
    return initializers;
}
 
Example #24
Source File: MockServer.java    From funcatron with Apache License 2.0 4 votes vote down vote up
public MockEmbeddedServletContainer(ServletContextInitializer[] initializers, int port) {
    this.initializers = initializers;
    this.port = port;
    initialize();
}
 
Example #25
Source File: MvcConfiguration.java    From oncokb with GNU Affero General Public License v3.0 4 votes vote down vote up
@Bean
public ServletContextInitializer sentryServletContextInitializer() {
    return new io.sentry.spring.SentryServletContextInitializer();
}
 
Example #26
Source File: LealoneTomcatServletWebServerFactory.java    From Lealone-Plugins with Apache License 2.0 4 votes vote down vote up
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
    return new LealoneTomcatWebServer(super.getWebServer(initializers));
}