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() 

Source Link

Document

Create a new DispatcherServlet that will create its own internal web application context based on defaults and values provided through servlet init-params.

Usage

From source file:de.fau.amos4.test.BaseWebApplicationContextTests.java

@Before
public void initDispatcherServlet() throws Exception {
    servlet = new DispatcherServlet() {
        private static final long serialVersionUID = 1L;

        @Override//w ww .j  a va2s  .c om
        protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
                throws BeansException {

            GenericWebApplicationContext gwac = new GenericWebApplicationContext();
            gwac.setParent(applicationContext);
            gwac.refresh();
            return gwac;
        }
    };

    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();

    MockServletContext servletContext = new MockServletContext("src/main/java/amos4/model",
            new FileSystemResourceLoader());

    servlet.init(new MockServletConfig(servletContext));
}

From source file:com.techtrip.dynbl.context.config.WebAppinitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    // Setup Context to Accept Annotated Classes on Input (including plain Spring {@code @Component}
    // Stereotypes in addition to JSR-330 Compliant Classes using {@code javax.inject}
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

    //context.setConfigLocation(APP_CONFIG_LOCATION);
    context.setConfigLocation(APP_CONFIG_LOCATION);

    /* /*from   ww  w .j a  v  a2  s .  c  o  m*/
    * Add a Spring Security Filter using the JEE6 Filter Registration Filter Method from {@code FilterRegistration) that allows filters to be registered
    *  and configured with the specified context
    */
    /*              
    FilterRegistration.Dynamic securityFilter = servletContext.addFilter(ProjectKeyValConsts.SECURITY_FILTER.getKey(), new DelegatingFilterProxy(ProjectKeyValConsts.SECURITY_FILTER.getValue()));
    securityFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, ProjectConsts.BASE_URL_MAPPING_PATTERN.getValue()); // where the filter will be applied
    */
    // Add a Character Encoding Filter that specifies an encoding for mapped requests
    FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter",
            new CharacterEncodingFilter());
    characterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, ROOT_CONTEXT); // where the filter will be applied
    characterEncodingFilter.setInitParameter("encoding", "UTF-8");
    characterEncodingFilter.setInitParameter("forceEncoding", Boolean.TRUE.toString());
    characterEncodingFilter.setAsyncSupported(true);

    servletContext.addListener(new ContextLoaderListener(context));
    servletContext.setInitParameter("defaultHtmlEscape", Boolean.TRUE.toString());

    DispatcherServlet servlet = new DispatcherServlet();

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

    /* TMT From JEE 6 API Docs:
    * Registers the given servlet instance with this ServletContext under the given servletName.
    * The registered servlet may be further configured via the returned ServletRegistration object. 
    */

    ServletRegistration.Dynamic appServlet = servletContext.addServlet(APP_SERVLET, servlet);
    appServlet.setLoadOnStartup(1);
    appServlet.setAsyncSupported(true);

    Set<String> mappingConflicts = appServlet.addMapping("/");

    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException(String.format(
                "The servlet named '%s' cannot be mapped to '/' under Tomcat versions <= 7.0.14", APP_SERVLET));
    }

    // TMT
    servletContext.addListener(new Log4jConfigListener());

    System.out.println("Application inplemented on Spring Version: " + SpringVersion.getVersion());

}

From source file:com.cfitzarl.cfjwed.Main.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    // Add spring security filter chain
    servletContext.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class)
            .addMappingForUrlPatterns(null, false, "/*");

    // Add Hibernate session binder
    servletContext.addFilter("jpaTransactionFilter", OpenEntityManagerInViewFilter.class)
            .addMappingForUrlPatterns(null, false, "/*");

    // Define application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(WebApplicationMvcConfigurer.class);
    rootContext.scan("com.cfitzarl.cfjwed");

    // Create a dispatcher servlet that loads the application context
    DispatcherServlet dispatcherServlet = new DispatcherServlet();
    dispatcherServlet.setApplicationContext(rootContext);

    // Add the dispatcher servlet to the servlet context and map it to /
    ServletRegistration.Dynamic servletRegister = servletContext.addServlet("dispatcher", dispatcherServlet);
    servletRegister.setLoadOnStartup(1);
    servletRegister.addMapping("/");

    servletContext.addListener(new ContextLoaderListener(rootContext));
}

From source file:org.urbantower.j4s.spring.ServletContextHandlerParser.java

/**
 * method parse 'dispatcher-servlet' and register it into handler
 *///from  w ww .ja v  a  2s .  c  o  m
private void registerDispatcherServlet(Element dispatcherElm, ServletHandler handler) {
    //get name
    String servletName = getServletName(dispatcherElm, DispatcherServlet.class);
    String contextConfigLocation = dispatcherElm.getAttribute("context-config-location");

    //register servlet
    DispatcherServlet dispatcherServlet = new DispatcherServlet();
    dispatcherServlet.setContextConfigLocation(contextConfigLocation);
    ServletHolder holder = new ServletHolder(servletName, dispatcherServlet);
    handler.addServlet(holder);

    //register mappings
    ServletMapping mapping = createMapping(dispatcherElm, handler, servletName);
    try {
        handler.addServletMapping(mapping);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.dlopes.stocks.facilitator.config.JsfMvcConfig.java

/**
 * create a Spring MVC dispatcher servlet so that we can slightly modify its
 * config within the environment automatically generated by spring boot
 * //from   w  w  w.ja  va2s  .c  o  m
 * Hint: if we don't do that there will be two instances and all modifications
 * to the config
 * 
 * @return the DispatcherServlet
 */
@Bean
public DispatcherServlet dispatcherServlet() {
    return new DispatcherServlet();
}

From source file:com.gradecak.alfresco.mvc.webscript.DispatcherWebscript.java

public void afterPropertiesSet() throws Exception {

    s = new DispatcherServlet() {

        private static final long serialVersionUID = -7492692694742840997L;

        @Override//  w  ww. j a  v a  2  s  .  c  om
        protected WebApplicationContext initWebApplicationContext() {
            WebApplicationContext wac = createWebApplicationContext(applicationContext);
            if (wac == null) {
                wac = super.initWebApplicationContext();
            }
            return wac;
        }

    };

    s.setContextConfigLocation(contextConfigLocation);
    s.init(new DelegatingServletConfig());

    if (this.serviceRegistry == null) {
        this.serviceRegistry = (ServiceRegistry) applicationContext.getBean("ServiceRegistry");
    }
    // logger.info("DispatcherWebScript initialized");
}

From source file:com.github.carlomicieli.nerdmovies.MockWebApplicationContextLoader.java

@Override
public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
    final MockServletContext servletContext = new MockServletContext(configuration.webapp(),
            new FileSystemResourceLoader());
    final MockServletConfig servletConfig = new MockServletConfig(servletContext, configuration.name());

    final AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webContext);
    webContext.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles());
    webContext.setServletConfig(servletConfig);
    webContext.setConfigLocations(mergedConfig.getLocations());
    webContext.register(mergedConfig.getClasses());

    // Create a DispatcherServlet that uses the previously established
    // WebApplicationContext.
    @SuppressWarnings("serial")
    final DispatcherServlet dispatcherServlet = new DispatcherServlet() {
        @Override/* w w  w.java 2 s  .  com*/
        protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
            return webContext;
        }
    };

    // Add the DispatcherServlet (and anything else you want) to the
    // context.
    // Note: this doesn't happen until refresh is called below.
    webContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            beanFactory.registerResolvableDependency(DispatcherServlet.class, dispatcherServlet);
            // Register any other beans here, including a ViewResolver if
            // you are using JSPs.
        }
    });

    // Have the context notify the servlet every time it is refreshed.
    webContext.addApplicationListener(
            new SourceFilteringListener(webContext, new ApplicationListener<ContextRefreshedEvent>() {
                @Override
                public void onApplicationEvent(ContextRefreshedEvent event) {
                    dispatcherServlet.onApplicationEvent(event);
                }
            }));

    // Prepare the context.
    webContext.refresh();
    webContext.registerShutdownHook();

    // Initialize the servlet.
    dispatcherServlet.setContextConfigLocation("");
    dispatcherServlet.init(servletConfig);

    return webContext;
}

From source file:com.iflytek.edu.cloud.frame.web.RestServiceWebApplicationInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    servletContext.setInitParameter("contextConfigLocation", "classpath*:META-INF/spring/*-context.xml");
    servletContext.setInitParameter("contextInitializerClasses",
            ProfileApplicationContextInitializer.class.getName());
    servletContext.addListener(new LogBackLoadConfigureListener());
    servletContext.addListener(new ContextLoaderListener());

    FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter",
            new CharacterEncodingFilter());
    EnumSet<DispatcherType> characterEncodingFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST,
            DispatcherType.FORWARD);//from w ww  .j  ava 2s .  com
    characterEncodingFilter.setInitParameter("encoding", "UTF-8");
    characterEncodingFilter.setInitParameter("forceEncoding", "true");
    characterEncodingFilter.addMappingForUrlPatterns(characterEncodingFilterDispatcherTypes, true, "/*");

    FilterRegistration.Dynamic openServiceFilter = servletContext.addFilter("openServiceFilter",
            new DelegatingFilterProxy());
    EnumSet<DispatcherType> openServiceFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST,
            DispatcherType.FORWARD);
    openServiceFilter.addMappingForUrlPatterns(openServiceFilterDispatcherTypes, true, "/api");

    if (EnvUtil.jdbcEnabled()) {
        FilterRegistration.Dynamic serviceMetricsFilter = servletContext.addFilter("serviceMetricsFilter",
                new DelegatingFilterProxy());
        EnumSet<DispatcherType> serviceMetricsFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST,
                DispatcherType.FORWARD);
        serviceMetricsFilter.addMappingForUrlPatterns(serviceMetricsFilterDispatcherTypes, true, "/api");
    }

    FilterRegistration.Dynamic CORSFilter = servletContext.addFilter("CORSFilter", new DelegatingFilterProxy());
    EnumSet<DispatcherType> CORSFilterDispatcherTypes = EnumSet.of(DispatcherType.REQUEST,
            DispatcherType.FORWARD);
    CORSFilter.addMappingForUrlPatterns(CORSFilterDispatcherTypes, true, "/api");

    if (EnvUtil.oauthEnabled()) {
        FilterRegistration.Dynamic springSecurityFilterChain = servletContext
                .addFilter("springSecurityFilterChain", new DelegatingFilterProxyExt());
        EnumSet<DispatcherType> springSecurityFilterChainDispatcherTypes = EnumSet.of(DispatcherType.REQUEST,
                DispatcherType.FORWARD);
        springSecurityFilterChain.addMappingForUrlPatterns(springSecurityFilterChainDispatcherTypes, true,
                "/api");
    } else {
        logger.info(
                "?oauth2???META-INF/res/profile.propertiesoauth2 profile");
    }

    ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("rest", new DispatcherServlet());
    dispatcherServlet.setLoadOnStartup(1);
    dispatcherServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    dispatcherServlet.setInitParameter("contextConfigLocation", "org.spring.rest");
    dispatcherServlet.setMultipartConfig(getMultiPartConfig());
    dispatcherServlet.addMapping("/api");

    ServletRegistration.Dynamic printProjectVersionServlet = servletContext
            .addServlet("printProjectVersionServlet", new PrintProjectVersionServlet());
    printProjectVersionServlet.setLoadOnStartup(Integer.MAX_VALUE);
}

From source file:org.geoserver.test.GeoServerAbstractTestSupport.java

protected DispatcherServlet getDispatcher() throws Exception {
    // create an instance of the spring dispatcher
    ServletContext context = applicationContext.getServletContext();

    MockServletConfig config = new MockServletConfig();
    config.setServletContext(context);//from ww w  . jav a2 s  .  c om
    config.setServletName("dispatcher");

    DispatcherServlet dispatcher = new DispatcherServlet();

    dispatcher.setContextConfigLocation(
            GeoServerAbstractTestSupport.class.getResource("dispatcher-servlet.xml").toString());
    dispatcher.init(config);

    return dispatcher;
}

From source file:org.polymap.service.geoserver.GeoServerWms.java

protected void initGeoServer() throws Exception {

    context = new PluginServletContext(getServletContext());
    log.debug("initGeoServer(): contextPath=" + context.getContextPath());

    ClassLoader threadLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(context.cl);

    try {//from www  .j  a  va  2s. com
        File cacheDir = GeoServerPlugin.getDefault().getCacheDir();
        dataDir = new File(cacheDir, Stringer.on(map.getLabel()).toFilename("_").toString());
        log.debug("    dataDir=" + dataDir.getAbsolutePath());
        dataDir.mkdirs();
        FileUtils.forceDeleteOnExit(dataDir);

        // web.xml
        context.setAttribute("serviceStrategy", "SPEED");
        context.setAttribute("contextConfigLocation",
                "classpath*:/applicationContext.xml classpath*:/applicationSecurityContext.xml");
        context.setAttribute("enableVersioning", "false");
        context.setAttribute("GEOSERVER_DATA_DIR", dataDir.getAbsoluteFile());

        try {
            servers.set(this);

            loaders.add(new LoggingStartupContextListener());
            loaders.add(new ContextLoaderListener());

            ServletContextEvent ev = new ServletContextEvent(context);
            for (Object loader : loaders) {
                ((ServletContextListener) loader).contextInitialized(ev);
            }
        } finally {
            servers.set(null);
        }

        dispatcher = new DispatcherServlet();
        log.debug("Dispatcher: " + dispatcher.getClass().getClassLoader());
        dispatcher.init(new ServletConfig() {

            public String getInitParameter(String name) {
                return GeoServerWms.this.getInitParameter(name);
            }

            public Enumeration getInitParameterNames() {
                return GeoServerWms.this.getInitParameterNames();
            }

            public ServletContext getServletContext() {
                return context;
            }

            public String getServletName() {
                return "dispatcher";
            }
        });
    } finally {
        Thread.currentThread().setContextClassLoader(threadLoader);
    }
}