Example usage for javax.servlet DispatcherType FORWARD

List of usage examples for javax.servlet DispatcherType FORWARD

Introduction

In this page you can find the example usage for javax.servlet DispatcherType FORWARD.

Prototype

DispatcherType FORWARD

To view the source code for javax.servlet DispatcherType FORWARD.

Click Source Link

Usage

From source file:io.gumga.security.WebConfigForTest.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

    servletContext.setInitParameter("javax.servlet.jsp.jstl.fmt.localizationContext", "messages");
    EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    characterEncodingFilter.setForceEncoding(true);
    FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding",
            characterEncodingFilter);//w w  w  . j a  v a 2  s  .c  o  m
    characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");

    rootContext.setServletContext(servletContext);
    rootContext.register(WebConfigForTest.class);
    rootContext.refresh();

}

From source file:io.gravitee.management.war.WebAppInitializer.java

@Override
public void onStartup(ServletContext context) throws ServletException {
    // initialize
    initialize();//w  w w.  j  a v  a2 s.  c o  m
    Properties prop = propertiesLoader.load();

    // REST configuration
    ServletRegistration.Dynamic servletRegistration = context.addServlet("REST",
            ServletContainer.class.getName());
    servletRegistration.addMapping("/management/*");
    servletRegistration.setLoadOnStartup(1);
    servletRegistration.setInitParameter("javax.ws.rs.Application", GraviteeApplication.class.getName());

    // Spring configuration
    System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME,
            prop.getProperty("security.type", "basic-auth"));
    context.addListener(new ContextLoaderListener());
    context.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    context.setInitParameter("contextConfigLocation", RestConfiguration.class.getName());

    // Spring Security filter
    context.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class)
            .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), false, "/*");
}

From source file:com.gosmarter.it.eis.config.ExcelERPWebApplicationInitializer.java

private void registerSpringSecurityFilterChain(ServletContext servletContext) {
    DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy("springSecurityFilterChain");
    FilterRegistration fr = servletContext.addFilter("securityFilter", delegatingFilterProxy);
    fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/*");
}

From source file:org.ireland.jnetty.dispatch.filter.FilterMapping.java

/**
 * True if the dispatcher is for FORWARD.
 *//*  w  ww  . jav a 2  s  .c  om*/
public boolean isForward() {
    return _dispatcherTypes != null && _dispatcherTypes.contains(DispatcherType.FORWARD);
}

From source file:fi.helsinki.opintoni.config.WebConfigurer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
    EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
            DispatcherType.ASYNC);/*from w  w w .  j a  va2  s .c  o  m*/
    if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_QA,
            Constants.SPRING_PROFILE_DEMO, Constants.SPRING_PROFILE_PRODUCTION)) {
        initMetrics(servletContext, dispatcherTypes);

        // Forces browser to send cookies with HTTPS connection only
        servletContext.getSessionCookieConfig().setSecure(true);
    }

    servletContext.getSessionCookieConfig().setName(Constants.SESSION_COOKIE_NAME);
    servletContext.getSessionCookieConfig().setDomain(appConfiguration.get("cookieDomain"));

    log.info("Web application fully configured");
}

From source file:com.dm.estore.config.WebAppInitializer.java

private void registerFilters(ServletContext servletContext) {
    FilterRegistration.Dynamic securityFilter = servletContext.addFilter(SECURITY_FILTER_NAME,
            new DelegatingFilterProxy());
    securityFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, REST_SERVLET_MAPPING);
    securityFilter.setAsyncSupported(true);

    FilterRegistration.Dynamic applicationFilter = servletContext.addFilter(APP_FILTER_NAME,
            new ApplicationFilter());
    applicationFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD),
            false, APP_FILTER_MAPPING);/*from   ww w  . j  av  a 2 s.c o m*/
    applicationFilter.setAsyncSupported(true);
}

From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelper.java

protected Response invokePlatformEndpoint(final String endpointPath, final String httpMethod,
        final Map<String, String> queryParameters) {

    Response response = new Response();

    // get servlet context and request dispatcher
    ServletContext servletContext = null;
    RequestDispatcher requestDispatcher = null;
    try {/*from   www  . j av a2  s  .  co m*/
        Object context = getContext();
        if (context instanceof ServletContext) {
            servletContext = (ServletContext) context;
            requestDispatcher = servletContext.getRequestDispatcher("/api" + endpointPath);
        }
    } catch (NoClassDefFoundError ex) {
        logger.error("Failed to get application servlet context", ex);
        return response;
    }

    if (requestDispatcher != null) {
        // create servlet request
        URL fullyQualifiedServerURL;
        try {
            fullyQualifiedServerURL = getUrl();
        } catch (MalformedURLException e) {
            logger.error("FullyQualifiedServerURL is incorrect");
            return response;
        }

        final InternalHttpServletRequest servletRequest = new InternalHttpServletRequest(httpMethod,
                fullyQualifiedServerURL, "/api", endpointPath);
        servletRequest.setAttribute("org.apache.catalina.core.DISPATCHER_TYPE", DispatcherType.FORWARD); //FORWARD = 2

        try {
            insertParameters(httpMethod, queryParameters, servletRequest);
        } catch (UnsupportedEncodingException e) {
            logger.error("Can't encode parameters");
            return response;
        }

        ServletRequestEvent servletRequestEvent = new ServletRequestEvent(servletContext, servletRequest);
        RequestContextListener requestContextListener = new RequestContextListener();
        requestContextListener.requestInitialized(servletRequestEvent);

        // create servlet response
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final InternalHttpServletResponse servletResponse = new InternalHttpServletResponse(outputStream);

        try {
            // used for calculating the response time
            long startTime = System.currentTimeMillis();

            requestDispatcher.forward(servletRequest, servletResponse);

            // get response time
            long responseTime = System.currentTimeMillis() - startTime;

            response.setStatusCode(servletResponse.getStatus());
            response.setResult(servletResponse.getContentAsString());
            response.setResponseTime(responseTime);
        } catch (ServletException ex) {
            logger.error("Failed ", ex);
            return response;
        } catch (IOException ex) {
            logger.error("Failed ", ex);
            return response;
        } finally {
            requestContextListener.requestDestroyed(servletRequestEvent);
        }

    }

    return response;
}

From source file:com.fluidops.iwb.server.HybridSearchServlet.java

/**
 * Retrieve the query from request, do the token based security check and
 * evaluate the query.//from ww  w . ja  va 2s . co  m
 * 
 * @param req
 * @param resp
 * @throws IOException, ServletException 
 */
protected void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // register search page
    String uri = null;
    if (req.getDispatcherType() == DispatcherType.FORWARD)
        uri = (String) req.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
    else
        uri = req.getRequestURI();

    // Done to avoid processing of a request from TimelineWidget.
    if (uri.endsWith("__history__.html")) {
        return;
    }

    FSession.registerPage(uri, FPage.class);

    FSession.removePage(req);

    // get session and page
    FSession session = FSession.getSession(req);
    FPage page;
    try {
        page = (FPage) session.getComponentById(uri, req);
    } catch (Exception e) {
        log.warn("Could not get the page for request: " + uri, e);
        resp.sendRedirect(RedirectService.getRedirectURL(RedirectType.PAGE_NOT_FOUND, req));
        return;
    }

    SearchPageContext pc = getPageContext();

    // register FPage
    pc.page = page;
    pc.session = session;

    // get and decode query
    pc.query = getQueryFromRequest(req);
    if (pc.query == null) {
        // use empty query if no query is given
        pc.query = "";
    }

    pc.query = pc.query.trim();
    PageContext.setThreadPageContext(pc);

    List<String> queryTargets = SearchProviderFactory.getDefaultQueryTargets();

    String[] vals;
    if ((vals = req.getParameterValues("queryTarget")) != null && (vals.length > 0)) {
        queryTargets = Lists.newArrayList(vals);
    }

    SparqlQueryType qt = null;

    // Currently, the special query language protocol can be passed in two ways:
    // - as a prefix to the query: e.g., "sql:".
    // - as a request parameter "queryLanguage".
    // If no query language is given explicitly, then the default routine is performed:
    // First, we check that the query is a valid SPARQL query and then, if it is not the case, it is interpreted as a 
    // keyword query.
    pc.queryLanguage = determineQueryLanguage(pc.query, req);

    // If the query language was provided as a prefix, we no longer need the prefix
    if (!pc.queryLanguage.equals("DEFAULT")
            && pc.query.toUpperCase().startsWith(pc.queryLanguage.toUpperCase() + ":")) {
        pc.query = pc.query.substring(pc.queryLanguage.length() + 1).trim();
    }

    if (pc.queryLanguage.equals("SPARQL") || pc.queryLanguage.equals("DEFAULT")) {
        try {
            qt = ReadDataManagerImpl.getSparqlQueryType(pc.query, true);
            // We managed to parse it as SPARQL, so it's SPARQL anyway.
            pc.queryLanguage = "SPARQL";
            // since ASK queries are used in bigowlim for several control functionalities
            // we do not want to support them right now. Same for UPDATE
            if (qt == SparqlQueryType.ASK || qt == SparqlQueryType.UPDATE) {
                error(resp, 403, "Not allowed to execute ASK or UPDATE queries.");
                return;
            }
        } catch (MalformedQueryException e) {
            // if the SPARQL prefix was provided explicitly: throw an error 
            if (pc.queryLanguage.equals("SPARQL")) {
                error(resp, 400, "Malformed query:\n\n" + pc.query + "\n\n" + e.getMessage());
                return;
            }
            // ignore: not a valid SPARQL query, treat it as keyword query
        }
    }

    //////////////////SECURITY CHECK/////////////////////////
    // remarks:
    // queries are checked, keywords and invalid queries are always allowed
    String securityToken = req.getParameter("st");
    if (!EndpointImpl.api().getUserManager().hasQueryPrivileges(pc.query, qt, securityToken)) {
        error(resp, 403, "Not enough rights to execute query.");
        return;
    }

    // value to be used in queries instead of ??
    String _resolveValue = req.getParameter("value");
    Value resolveValue = _resolveValue != null ? ValueFactoryImpl.getInstance().createURI(_resolveValue) : null;

    boolean infer = false; // default value for inferencing is false

    if (req.getParameter("infer") != null)
        infer = Boolean.parseBoolean(req.getParameter("infer"));

    pc.infer = infer;

    List<ErrorRecord> errorRecords = Lists.newArrayListWithCapacity(queryTargets.size());

    // empty query --> empty result
    if (pc.query.isEmpty()) {
        pc.queryLanguage = "KEYWORD";
        pc.queryType = "KEYWORD";

        try {
            pc.queryResult = new MutableTupleQueryResultImpl(new TupleQueryResultImpl(
                    Collections.<String>emptyList(), Collections.<BindingSet>emptyList().iterator()));
        } catch (QueryEvaluationException e) {
            log.warn("Could not produce a mutable tuple query result");
            log.debug("Details: ", e);
        }
    }
    // allowed SPARQL queries
    else if (pc.queryLanguage.equals("SPARQL")) {
        pc.queryType = qt.toString();

        QueryResult<?> queryRes = null;

        List<SparqlSearchProvider> sparqlProviders = SearchProviderFactory.getInstance()
                .getSparqlSearchProviders(queryTargets);

        for (SparqlSearchProvider sparqlProvider : sparqlProviders) {

            try {
                QueryResult<?> currentQueryRes = sparqlProvider.search(pc.query, qt, resolveValue, infer);
                queryRes = ReadDataManagerImpl.mergeQueryResults(queryRes, currentQueryRes);
            } catch (MalformedQueryException e) {
                // If a SPARQL query is malformed, no need to send it to all search providers
                error(resp, 400, e.getMessage());
                return;
            } catch (Exception e) {
                errorRecords.add(createErrorRecord(e, sparqlProvider, pc));
            }

        }

        if (queryRes == null) {
            if (qt == SparqlQueryType.CONSTRUCT) {
                queryRes = new GraphQueryResultImpl(
                        EndpointImpl.api().getNamespaceService().getRegisteredNamespacePrefixes(),
                        Collections.<Statement>emptyList());
            } else {
                queryRes = new MutableTupleQueryResultImpl(Lists.newArrayList("Results"),
                        Collections.<BindingSet>emptyList());
            }
        }
        pc.queryResult = queryRes;

    }
    // query with a pre-defined custom protocol
    else if (!pc.queryLanguage.equals("DEFAULT")) {
        pc.queryType = "KEYWORD";

        QueryResult<?> queryRes = null;

        List<SearchProvider> providers = SearchProviderFactory.getInstance()
                .getSearchProvidersSupportingQueryLanguage(queryTargets, pc.queryLanguage);

        QueryResult<?> currentQueryResult;

        for (SearchProvider provider : providers) {
            // If the query protocol was provided, we assume that the target knows how to deal with it.
            try {
                currentQueryResult = provider.search(pc.queryLanguage, pc.query);
                queryRes = ReadDataManagerImpl.mergeQueryResults(queryRes, currentQueryResult);
            } catch (Exception e) {
                errorRecords.add(createErrorRecord(e, provider, pc));
            }
        }

        pc.queryResult = (queryRes != null) ? queryRes : createEmptyKeywordQueryResult();

    }
    // keyword query
    else {

        try {
            handleKeywordQuery(pc, queryTargets);

        } catch (ParseException e) {
            error(resp, 400, "Malformed keyword query:\n\n" + pc.query + "\n\n" + e.getMessage());
        } catch (SearchException e) {
            errorRecords.add(createErrorRecord(e, pc));
        }
    }

    resp.setStatus(HttpServletResponse.SC_OK);

    // calculate facets
    // legacy code faceted search, currently not active
    //         String facetsAsString = "";
    //         if (Config.getConfig().getFacetedSearch().equals("standard")) 
    //         {
    //            FacetCalculator facetter = new FacetCalculator( pc );
    //            FContainer facetContainer = facetter.getFacetContainer();
    //            page.register(facetContainer);
    //            facetsAsString = facetContainer.htmlAnchor().toString();
    //            facetContainer.drawAdvHeader(true);
    //            facetContainer.drawHeader(false);
    //         }

    // page title
    pc.title = (pc.queryLanguage.equals("SPARQL") && !pc.queryType.equals("KEYWORD") || pc.query.isEmpty())
            ? "Search result"
            : "Search result: " + StringEscapeUtils.escapeHtml(pc.query);

    // TODO: activeLabel

    // select widgets to display search results
    selectWidgets(pc, infer);

    // layout result page
    populateContainer(pc, errorRecords);

    // print response
    EndpointImpl.api().getPrinter().print(pc, resp);
}

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

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {//  w  w  w . j av a2s. 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);
    }
}