Example usage for javax.servlet ServletContext addServlet

List of usage examples for javax.servlet ServletContext addServlet

Introduction

In this page you can find the example usage for javax.servlet ServletContext addServlet.

Prototype

public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass);

Source Link

Document

Adds the servlet with the given name and class type to this servlet context.

Usage

From source file:com.miserablemind.butter.bootstrap.AppInitializer.java

/**
 * Implements {@link WebApplicationInitializer} onStartup to initialize the system.
 * It registers and configures {@link RootContext}, {@link WebSecurityContext}, and app specific contexts.
 * It also initializes the {@link Log4jConfigListener}.
 *
 * @param container ServletContext//  w ww .j  av  a2s  . c om
 */
@Override
public void onStartup(ServletContext container) {

    //Make the logger read settings from main properties file
    container.setInitParameter("log4jConfigLocation", "classpath:system.properties");
    container.addListener(new Log4jConfigListener());

    //Root Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(RootContext.class);
    container.addListener(new ContextLoaderListener(rootContext));

    //Spring Security context
    AnnotationConfigWebApplicationContext securityContext = new AnnotationConfigWebApplicationContext();
    securityContext.register(WebSecurityContext.class);
    DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("springSecurityFilterChain");
    container.addFilter("springSecurityFilterChain", filterProxy).addMappingForUrlPatterns(null, false, "*");

    //Dispatcher Servlet context
    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(ButterAppMVCContext.class);

    //Register and map the dispatcher servlet
    DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
    ServletRegistration.Dynamic dispatcher = container.addServlet("mvc-dispatcher", dispatcherServlet);
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

}

From source file:org.davidmendoza.demo.config.StartUpConfig.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(ComponentConfig.class, DataConfig.class, MailConfig.class, WebConfig.class);
    context.setDisplayName("DemoApp");

    FilterRegistration.Dynamic sitemeshFilter = servletContext.addFilter("sitemeshFilter",
            new ConfigurableSiteMeshFilter());
    sitemeshFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

    FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter",
            new CharacterEncodingFilter());
    characterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    characterEncodingFilter.setInitParameter("encoding", "UTF-8");
    characterEncodingFilter.setInitParameter("forceEncoding", "true");

    servletContext.addListener(new ContextLoaderListener(context));
    //servletContext.setInitParameter("defaultHtmlEscape", "false");

    DispatcherServlet servlet = new DispatcherServlet();
    // no explicit configuration reference here: everything is configured in the root container for simplicity
    servlet.setContextConfigLocation("");

    ServletRegistration.Dynamic appServlet = servletContext.addServlet("appServlet", servlet);
    appServlet.setLoadOnStartup(1);//from   w  w  w .j ava 2  s  . co  m
    appServlet.setAsyncSupported(true);

    Set<String> mappingConflicts = appServlet.addMapping("/");
    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException("'appServlet' cannot be mapped to '/' under Tomcat versions <= 7.0.14");
    }
}

From source file:com.local.ask.controller.WebAppInitializer.java

@Override
public void onStartup(ServletContext container) {

    CharacterEncodingFilter encodingFilter = new org.springframework.web.filter.CharacterEncodingFilter();
    encodingFilter.setEncoding("UTF-8");
    encodingFilter.setForceEncoding(false);
    FilterRegistration.Dynamic encodingFilterDinamic = container.addFilter("charEncodingFilter",
            encodingFilter);//from  www . j av a  2 s .  c  om
    encodingFilterDinamic.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(WebConfig.class);
    rootContext.register(SecurityConfig.class);

    // Manage the lifecycle of the root application context
    container.addListener(new ContextLoaderListener(rootContext));

    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(HomeController.class);
    dispatcherContext.register(LoginController.class);
    dispatcherContext.register(PostController.class);
    dispatcherContext.register(SignUpController.class);
    dispatcherContext.register(ContactUsController.class);

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher",
            new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

    DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
    filterProxy.setTargetFilterLifecycle(true);
    container.addFilter("shiroFilter", filterProxy).addMappingForUrlPatterns(null, false, "/*");

    // encoding filter
}

From source file:cz.muni.fi.editor.webapp.config.init.EditorApplicationInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    String bootLogo = "  __  __      _            _       _                   _ _ _             \n"
            + " |  \\/  |    | |          | |     | |                 | (_) |            \n"
            + " | \\  / | ___| |_ __ _  __| | __ _| |_ __ _    ___  __| |_| |_ ___  _ __ \n"
            + " | |\\/| |/ _ \\ __/ _` |/ _` |/ _` | __/ _` |  / _ \\/ _` | | __/ _ \\| '__|\n"
            + " | |  | |  __/ || (_| | (_| | (_| | || (_| | |  __/ (_| | | || (_) | |   \n"
            + " |_|  |_|\\___|\\__\\__,_|\\__,_|\\__,_|\\__\\__,_|  \\___|\\__,_|_|\\__\\___/|_|   \n"
            + "                                                                         \n"
            + "                                                                         ";

    System.out.println(ANSI_YELLOW + bootLogo + ANSI_RESET);

    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.getEnvironment().setActiveProfiles("production");
    rootContext.register(WebAppConfiguration.class, SecurityConfig.class);

    servletContext.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(MvcConfiguration.class, WebSocketSecurityConfiguration.class);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);/*  w ww.  ja v  a  2 s .  co m*/
    dispatcher.setAsyncSupported(true);
    dispatcher.addMapping("/");

    servletContext.addFilter("encodingFilter", new CharacterEncodingFilter("UTF-8", true))
            .addMappingForUrlPatterns(null, false, "/*");

    servletContext.addFilter("httpMethodFilter", new HiddenHttpMethodFilter()).addMappingForUrlPatterns(null,
            true, "/*");

}

From source file:org.alfresco.bm.web.WebApp.java

@Override
public void onStartup(ServletContext container) {
    // Grab the server capabilities, otherwise just use the java version
    String javaVersion = System.getProperty("java.version");
    String systemCapabilities = System.getProperty(PROP_SYSTEM_CAPABILITIES, javaVersion);

    String appDir = new File(".").getAbsolutePath();
    String appContext = container.getContextPath();
    String appName = container.getContextPath().replace(SEPARATOR, "");

    // Create an application context (don't start, yet)
    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    ctx.setConfigLocations(new String[] { "classpath:config/spring/app-context.xml" });

    // Pass our properties to the new context
    Properties ctxProperties = new Properties();
    {//from  w w w. j  a va2 s . com
        ctxProperties.put(PROP_SYSTEM_CAPABILITIES, systemCapabilities);
        ctxProperties.put(PROP_APP_CONTEXT_PATH, appContext);
        ctxProperties.put(PROP_APP_DIR, appDir);
    }
    ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource(appName, ctxProperties));
    // Override all properties with system properties
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system", System.getProperties()));
    // Bind to shutdown
    ctx.registerShutdownHook();

    ContextLoaderListener ctxLoaderListener = new ContextLoaderListener(ctx);
    container.addListener(ctxLoaderListener);

    ServletRegistration.Dynamic jerseyServlet = container.addServlet("jersey-serlvet", SpringServlet.class);
    jerseyServlet.setInitParameter("com.sun.jersey.config.property.packages", "org.alfresco.bm.rest");
    jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
    jerseyServlet.addMapping("/api/*");
}

From source file:be.wolkmaan.klimtoren.web.config.WebAppInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    // Create the root appcontext
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(RootConfig.class);
    rootContext.register(PersistenceConfig.class);

    // Manage the lifecycle of the root appcontext
    servletContext.addListener(new ContextLoaderListener(rootContext));
    servletContext.setInitParameter("defaultHtmlEscape", "true");

    this.zkLoaderServlet(servletContext);

    // now the config for the Dispatcher servlet
    AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
    mvcContext.register(WebMvcConfig.class);

    // Filters/*from  ww  w  .  j  ava 2s . c o  m*/
    // http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/filter/package-summary.html
    // Enables support for DELETE and PUT request methods with web browser
    // clients
    // http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/filter/HiddenHttpMethodFilter.html
    FilterRegistration.Dynamic fr = servletContext.addFilter("hiddenHttpMethodFilter",
            new HiddenHttpMethodFilter());
    fr.addMappingForUrlPatterns(null, true, "/*");

    fr = servletContext.addFilter("encodingFilter", new CharacterEncodingFilter());
    fr.setInitParameter("encoding", "UTF-8");
    fr.setInitParameter("forceEncoding", "true");
    fr.addMappingForUrlPatterns(null, true, "/*");

    // The main Spring MVC servlet.
    ServletRegistration.Dynamic appServlet = servletContext.addServlet("appServlet",
            new DispatcherServlet(mvcContext));
    appServlet.setLoadOnStartup(2);
    Set<String> mappingConflicts = appServlet.addMapping("/");

    if (!mappingConflicts.isEmpty()) {
        for (String s : mappingConflicts) {
            logger.error("Mapping conflict: " + s);
        }
        throw new IllegalStateException("'appServlet' cannot be mapped to '/' under Tomcat versions <= 7.0.14");
    }

    HttpSessionListener zkCleanUp = new HttpSessionListener();
    servletContext.addListener(zkCleanUp);

    this.logbackServlet(servletContext);

    this.zkUpdateServlet(servletContext);
}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebContextLoader.java

protected void registerFrontAppServlet(ServletContext servletContext) {
    boolean hasFrontApp = false;
    try {/*from  w w w .  java  2s  .  c o m*/
        hasFrontApp = servletContext.getResource("/" + FRONT_CONTEXT_NAME) != null;
    } catch (MalformedURLException e) {
        //Do nothing
    }
    if (hasFrontApp) {
        String contextPath = servletContext.getContextPath();
        String baseUrl = System.getProperty("cuba.front.baseUrl");
        if (baseUrl == null || baseUrl.length() == 0) {
            String path = "/" + FRONT_CONTEXT_NAME + "/";
            System.setProperty("cuba.front.baseUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        String apiUrl = System.getProperty("cuba.front.apiUrl");
        if (apiUrl == null || apiUrl.length() == 0) {
            String path = "/rest/";
            System.setProperty("cuba.front.apiUrl", "/".equals(contextPath) ? path : contextPath + path);
        }
        DispatcherServlet frontServlet;
        try {
            Class frontServletClass = ReflectionHelper.getClass("com.haulmont.cuba.web.sys.AppFrontServlet");
            frontServlet = (DispatcherServlet) ReflectionHelper.newInstance(frontServletClass,
                    FRONT_CONTEXT_NAME, (Supplier<ApplicationContext>) AppContext::getApplicationContext);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Unable to instantiate app front servlet", e);
        }
        ServletRegistration.Dynamic cubaServletReg = servletContext.addServlet("app_front_servlet",
                frontServlet);
        cubaServletReg.setLoadOnStartup(3);
        cubaServletReg.setAsyncSupported(true);
        cubaServletReg.addMapping(String.format("/%s/*", FRONT_CONTEXT_NAME));
    }
}

From source file:com.zxy.commons.hystrix.web.HystrixInitializer.java

/**
 * {@inheritDoc}/*from w w  w.  j ava  2 s .  co  m*/
 */
public void onStartup(ServletContext container) throws ServletException {
    //        WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(container);
    Properties properties = load();
    String enabled = properties.getProperty(HystrixProperties.HYSTRIX_ENABLED);
    String streamEnabled = properties.getProperty(HystrixProperties.HYSTRIX_STREAM_ENABLED);
    if ((StringUtils.isBlank(enabled) || "true".equalsIgnoreCase(enabled))
            && (StringUtils.isBlank(streamEnabled) || "true".equalsIgnoreCase(streamEnabled))) {

        // AnnotationConfigWebApplicationContext ctx = new
        // AnnotationConfigWebApplicationContext();
        // ctx.register(AppConfig.class);
        // ctx.setServletContext(container);

        // ServletRegistration.Dynamic servlet =
        // container.addServlet("dispatcher", new DispatcherServlet(ctx));
        // WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(container);
        // servlet.setLoadOnStartup(1);
        // servlet.addMapping("/");

        FilterRegistration.Dynamic hystrixRequestContextServletFilter = container
                .addFilter("HystrixRequestContextServletFilter", new HystrixRequestContextServletFilter());
        hystrixRequestContextServletFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true,
                "/*");

        FilterRegistration.Dynamic hystrixRequestLogViaResponseHeaderServletFilter = container.addFilter(
                "HystrixRequestLogViaResponseHeaderServletFilter",
                new HystrixRequestLogViaResponseHeaderServletFilter());
        hystrixRequestLogViaResponseHeaderServletFilter
                .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

        ServletRegistration.Dynamic hystrixMetricsStreamServlet = container
                .addServlet("HystrixMetricsStreamServlet", new HystrixMetricsStreamServlet());
        hystrixMetricsStreamServlet.addMapping("/hystrix.stream");

        // ServletRegistration.Dynamic proxyStreamServlet =
        // container.addServlet("ProxyStreamServlet", new
        // ProxyStreamServlet());
        // proxyStreamServlet.addMapping("/proxy.stream");
    }
}

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {/* w w w  .j  a  v a  2  s  .c o  m*/
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:be.fedict.eid.idp.webapp.IdentityProviderServletContextListener.java

private void initProtocolServices(ServletContextEvent event) {

    ServletContext servletContext = event.getServletContext();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    List<IdentityProviderProtocolType> identityProviderProtocolTypes = this.protocolServiceManager
            .getProtocolServices();//from ww w  .j a  v  a  2 s . co  m

    Map<String, String> wsEndpointsMap = new HashMap<String, String>();

    for (IdentityProviderProtocolType identityProviderProtocolType : identityProviderProtocolTypes) {
        String name = identityProviderProtocolType.getName();
        LOG.debug("initializing protocol service: " + name);

        // register endpoints
        EndpointsType endpoints = identityProviderProtocolType.getEndpoints();
        if (null != endpoints) {
            for (EndpointType endpoint : endpoints.getEndpoint()) {
                String contextPath = endpoint.getContextPath();
                String servletClassName = endpoint.getServletClass();
                LOG.debug("initializing on context path: " + contextPath + " servlet " + servletClassName);
                Class<?> servletClass;
                try {
                    servletClass = classLoader.loadClass(servletClassName);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("could not load the servlet class: " + servletClassName);
                }
                if (!Servlet.class.isAssignableFrom(servletClass)) {
                    throw new RuntimeException("not a servlet class: " + servletClassName);
                }
                String servletName = name + contextPath;
                LOG.debug("servlet name: " + servletName);
                @SuppressWarnings("unchecked")
                Dynamic dynamic = servletContext.addServlet(servletName,
                        (Class<? extends Servlet>) servletClass);
                String urlPattern = IdentityProviderProtocolService.ENDPOINT_CONTEXT_PATH + contextPath;
                dynamic.addMapping(urlPattern);
            }
        }

        // WS endpoints
        WSEndpointsType wsEndpoints = identityProviderProtocolType.getWSEndpoints();
        if (null != wsEndpoints) {
            for (WSEndpointType wsEndpoint : wsEndpoints.getWSEndpoint()) {

                String contextPath = wsEndpoint.getContextPath();
                String wsImplClass = wsEndpoint.getWSImplClass();
                LOG.debug("WS Endpoint: path=" + contextPath + " impl=" + wsImplClass);
                wsEndpointsMap.put(contextPath, wsImplClass);
            }
        }

        // initialize protocol specific attribute URIs
        LOG.debug("initializing protocol specific attribute URIs");
        IdentityProviderProtocolService protocolService = this.protocolServiceManager
                .getProtocolService(identityProviderProtocolType);

        for (AttributeEntity attribute : this.attributeService.listAttributes()) {

            this.attributeService.createAttributeUri(protocolService.getId(), attribute.getUri(),
                    protocolService.findAttributeUri(attribute.getUri()));
        }
    }

    // register JAX-WS runtime if necessary
    if (!wsEndpointsMap.isEmpty()) {

        // WSServlet class
        Class<?> wsServletClass;
        try {
            wsServletClass = classLoader.loadClass("com.sun.xml.ws.transport.http.servlet.WSServlet");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        @SuppressWarnings("unchecked")
        Dynamic dynamic = servletContext.addServlet("WSServlet", (Class<? extends Servlet>) wsServletClass);
        String urlPattern = IdentityProviderProtocolService.WS_ENDPOINT_CONTEXT_PATH + "/*";
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping(urlPattern);

        // intialize WS endpoints
        initWsEndpoints(servletContext, wsEndpointsMap);

    }
}