Example usage for org.springframework.web.servlet DispatcherServlet DispatcherServlet

List of usage examples for org.springframework.web.servlet DispatcherServlet DispatcherServlet

Introduction

In this page you can find the example usage for org.springframework.web.servlet DispatcherServlet DispatcherServlet.

Prototype

public DispatcherServlet(WebApplicationContext webApplicationContext) 

Source Link

Document

Create a new DispatcherServlet with the given web application context.

Usage

From source file:org.appverse.web.framework.backend.frontfacade.websocket.support.TomcatWebSocketTestServer.java

@Override
public void deployConfig(WebApplicationContext cxt) {
    this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
    this.context.addApplicationListener(WS_APPLICATION_LISTENER);
    Tomcat.addServlet(context, "dispatcherServlet", new DispatcherServlet(cxt));
    this.context.addServletMapping("/", "dispatcherServlet");
}

From source file:com.amazonaws.serverless.proxy.spring.LambdaSpringApplicationInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    applicationContext.setServletContext(servletContext);

    dispatcherConfig = new DefaultDispatcherConfig(servletContext);
    applicationContext.setServletConfig(dispatcherConfig);

    // Configure the listener for the request handled events. All we do here is release the latch
    applicationContext.addApplicationListener(new ApplicationListener<ServletRequestHandledEvent>() {
        @Override//w  w  w  . j a va  2  s . c  o m
        public void onApplicationEvent(ServletRequestHandledEvent servletRequestHandledEvent) {
            try {
                currentResponse.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Could not flush response buffer", e);
            }
        }
    });

    // Manage the lifecycle of the root application context
    this.addListener(new ContextLoaderListener(applicationContext));

    // Register and map the dispatcher servlet
    dispatcherServlet = new DispatcherServlet(applicationContext);

    if (refreshContext) {
        dispatcherServlet.refresh();
    }

    dispatcherServlet.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
    dispatcherServlet.init(dispatcherConfig);

    notifyStartListeners(servletContext);
}

From source file:com.kixeye.chassis.transport.http.HttpTransportConfiguration.java

@Bean(initMethod = "start", destroyMethod = "stop")
@Order(0)//ww w  . j  a v a 2  s . c  o m
public Server httpServer(@Value("${http.enabled:false}") boolean httpEnabled,
        @Value("${http.hostname:}") String httpHostname, @Value("${http.port:-1}") int httpPort,

        @Value("${https.enabled:false}") boolean httpsEnabled,
        @Value("${https.hostname:}") String httpsHostname, @Value("${https.port:-1}") int httpsPort,
        @Value("${https.selfSigned:false}") boolean selfSigned,
        @Value("${https.mutualSsl:false}") boolean mutualSsl,

        @Value("${https.keyStorePath:}") String keyStorePath,
        @Value("${https.keyStoreData:}") String keyStoreData,
        @Value("${https.keyStorePassword:}") String keyStorePassword,
        @Value("${https.keyManagerPassword:}") String keyManagerPassword,

        @Value("${https.trustStorePath:}") String trustStorePath,
        @Value("${https.trustStoreData:}") String trustStoreData,
        @Value("${https.trustStorePassword:}") String trustStorePassword,

        @Value("${https.excludedCipherSuites:}") String[] excludedCipherSuites,

        ConfigurableWebApplicationContext webApplicationContext) throws Exception {

    // set up servlets
    ServletContextHandler context = servletContextHandler();

    // create a new child application context
    AnnotationConfigWebApplicationContext childApplicationContext = (AnnotationConfigWebApplicationContext) transportWebMvcContext(
            webApplicationContext, context).getContext();

    // register swagger
    childApplicationContext.getBean(SwaggerRegistry.class).registerSwagger(context,
            getObjectMappers(webApplicationContext));

    // configure the spring mvc dispatcher
    DispatcherServlet dispatcher = new DispatcherServlet(childApplicationContext);

    // enable gzip
    context.addFilter(GzipFilter.class, "/*", null);

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");
    if (healthCheckRegistry != null) {
        context.addServlet(new ServletHolder(new HealthServlet(healthCheckRegistry)), "/healthcheck");
    }

    // create the server
    Server server;
    if (metricRegistry == null || !monitorThreadpool) {
        server = new Server();

        server.setHandler(context);
    } else {
        server = new Server(new InstrumentedQueuedThreadPool(metricRegistry));

        InstrumentedHandler instrumented = new InstrumentedHandler(metricRegistry);
        instrumented.setHandler(context);

        server.setHandler(instrumented);
    }

    // set up connectors
    if (httpEnabled) {
        InetSocketAddress address = StringUtils.isBlank(httpHostname) ? new InetSocketAddress(httpPort)
                : new InetSocketAddress(httpHostname, httpPort);

        JettyConnectorRegistry.registerHttpConnector(server, address);
    }

    if (httpsEnabled) {
        InetSocketAddress address = StringUtils.isBlank(httpsHostname) ? new InetSocketAddress(httpsPort)
                : new InetSocketAddress(httpsHostname, httpsPort);

        JettyConnectorRegistry.registerHttpsConnector(server, address, selfSigned, mutualSsl, keyStorePath,
                keyStoreData, keyStorePassword, keyManagerPassword, trustStorePath, trustStoreData,
                trustStorePassword, excludedCipherSuites);
    }

    return server;
}

From source file:com.kabiliravi.kaman.web.KamanApplicationInitializer.java

private void registerDispatcherServlet(final ServletContext servletContext) {
    WebApplicationContext dispatcherContext = createContext(WebMvcContextConfiguration.class);
    servletContext.addListener(new ContextLoaderListener(dispatcherContext));
    servletContext.addListener(new RequestContextListener());
    DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
    ServletRegistration.Dynamic dispatcher;
    dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet);
    dispatcher.setLoadOnStartup(1);//from   w ww .j ava  2 s  . c o m
    dispatcher.addMapping("/");
}

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

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {//w  ww  .j av a2  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:edu.stanford.epad.epadws.Main.java

/**
 * Function for setting up Spring Context with embedded Jetty
 * // w  ww  .  j a  v a  2s.co  m
 */
private static ServletContextHandler getServletContextHandler(WebApplicationContext context)
        throws IOException {
    ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setErrorHandler(null);
    contextHandler.setContextPath(CONTEXT_PATH);
    contextHandler.addServlet(new ServletHolder(new DispatcherServlet(context)), MAPPING_URL);
    contextHandler.addEventListener(new ContextLoaderListener(context));
    //contextHandler.setResourceBase(EPADConfig.getEPADWebServerResourcesDir());
    return contextHandler;
}

From source file:org.jumpmind.metl.ui.init.AppInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    Properties properties = loadProperties();
    AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
    applicationContext.scan("org.jumpmind.metl");
    MutablePropertySources sources = applicationContext.getEnvironment().getPropertySources();
    sources.addLast(new PropertiesPropertySource("passed in properties", properties));
    servletContext.addListener(new ContextLoaderListener(applicationContext));
    servletContext.addListener(this);
    servletContext.addListener(new RequestContextListener());

    AnnotationConfigWebApplicationContext dispatchContext = new AnnotationConfigWebApplicationContext();
    dispatchContext.setParent(applicationContext);
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(dispatchContext));
    dispatcher.setLoadOnStartup(1);//w  ww . j a v  a  2 s  .c o m
    dispatcher.addMapping("/api/*");
    applicationContextRef.set(dispatchContext);

    ServletRegistration.Dynamic apidocs = servletContext.addServlet("apidocs", DefaultServlet.class);
    apidocs.addMapping("/api.html", "/doc/*");

    ServletRegistration.Dynamic vaadin = servletContext.addServlet("vaadin", AppServlet.class);
    vaadin.setAsyncSupported(true);
    vaadin.setInitParameter("org.atmosphere.cpr.asyncSupport", JSR356AsyncSupport.class.getName());
    vaadin.setInitParameter("beanName", "appUI");
    vaadin.addMapping("/*");
}

From source file:org.kuali.coeus.sys.framework.config.KcConfigurer.java

@Override
protected void doAdditionalModuleStartLogic() throws Exception {
    if (StringUtils.isNotBlank(dispatchServletName)) {
        DispatcherServlet loaderServlet = new DispatcherServlet(
                (WebApplicationContext) ((SpringResourceLoader) rootResourceLoader.getResourceLoaders().get(0))
                        .getContext());/*from  w w  w  . java2 s. c  om*/
        ServletRegistration registration = getServletContext().addServlet(dispatchServletName, loaderServlet);
        registration.addMapping("/" + dispatchServletName + "/*");
        for (String filterName : filtersToMap) {
            FilterRegistration filter = getServletContext().getFilterRegistration(filterName);
            filter.addMappingForServletNames(null, true, dispatchServletName);
        }
        if (enableSpringSecurity) {
            DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(SPRING_SECURITY_FILTER_CHAIN,
                    (WebApplicationContext) ((SpringResourceLoader) rootResourceLoader.getResourceLoaders()
                            .get(0)).getContext());
            FilterRegistration.Dynamic securityFilter = getServletContext()
                    .addFilter(KC_PREFIX + getModuleName() + SPRING_SECURITY_FILTER_PROXY, filterProxy);
            securityFilter.addMappingForServletNames(null, true, dispatchServletName);
        }
    }
}

From source file:org.springframework.web.socket.TomcatWebSocketTestServer.java

@Override
public void deployConfig(WebApplicationContext wac, Filter... filters) {
    Assert.state(this.port != -1, "setup() was never called.");
    this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
    this.context.addApplicationListener(WsContextListener.class.getName());
    Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true);
    this.context.addServletMappingDecoded("/", "dispatcherServlet");
    for (Filter filter : filters) {
        FilterDef filterDef = new FilterDef();
        filterDef.setFilterName(filter.getClass().getName());
        filterDef.setFilter(filter);/*from w  w w .  j a  v a  2 s  . co m*/
        filterDef.setAsyncSupported("true");
        this.context.addFilterDef(filterDef);
        FilterMap filterMap = new FilterMap();
        filterMap.setFilterName(filter.getClass().getName());
        filterMap.addURLPattern("/*");
        filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC");
        this.context.addFilterMap(filterMap);
    }
}

From source file:org.springframework.xd.dirt.server.AdminServer.java

/**
 * Create an embedded Tomcat instance and have it run the WebApplicationContext
 *//*from   ww  w . j a v  a 2s  .c o m*/
@Override
public void afterPropertiesSet() {
    this.scheduler.setPoolSize(3);
    this.scheduler.initialize();
    this.tomcat.setPort(this.port);
    tomcatContext = this.tomcat.addContext(this.contextPath, new File(".").getAbsolutePath());
    this.webApplicationContext.setServletContext(tomcatContext.getServletContext());
    this.webApplicationContext.refresh();

    // Options requests should be handled by StreamServer, not Tomcat
    // in order to handle CORS requests
    DispatcherServlet servlet = new DispatcherServlet(this.webApplicationContext);
    servlet.setDispatchOptionsRequest(true);
    Tomcat.addServlet(tomcatContext, this.servletName, servlet);
    tomcatContext.addServletMapping("/", this.servletName);

    FilterDef filterDef = new FilterDef();
    filterDef.setFilterClass(HttpPutFormContentFilter.class.getName());
    filterDef.setFilterName("httpPut");
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName("httpPut");
    filterMap.addServletName(servletName);
    tomcatContext.addFilterDef(filterDef);
    tomcatContext.addFilterMap(filterMap);

    if (logger.isInfoEnabled()) {
        logger.info("initialized server: context=" + this.contextPath + ", servlet=" + this.servletName);
    }
}