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: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/*w  ww  .ja  v a  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:net.przemkovv.sphinx.config.ApplicationInitializer.java

public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(ApplicationConfig.class, JpaConfig.class);
    //        rootContext.refresh();
    rootContext.setDisplayName("Sphinx Web Application");

    servletContext.addListener(new ContextLoaderListener(rootContext));
    //        servletContext.addListener(new HttpSessionEventPublisher());

    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(WebMvcConfig.class);

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("Spring MVC Servlet",
            new DispatcherServlet(dispatcherContext));
    dispatcher.addMapping("/app/");
    dispatcher.setLoadOnStartup(1);/*from   www  . j  a  v  a 2s.co  m*/

    //        servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
    //                .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    servletContext.addFilter("UrlRewriteFilter", new UrlRewriteFilter()).addMappingForUrlPatterns(null, true,
            "/*");
    servletContext.addFilter("HttpMethodFilter", new HiddenHttpMethodFilter()).addMappingForUrlPatterns(null,
            true, "/*");
    servletContext.addFilter("HttpPutFormContentFilter", new HttpPutFormContentFilter())
            .addMappingForUrlPatterns(null, true, "/*");

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

    FilterRegistration.Dynamic dustCompilingFilter = servletContext.addFilter("dustCompilingFilter",
            new DustCompilingFilter());
    dustCompilingFilter.setInitParameter("templateNameRegex", "/template/(.*).dust.js$");
    dustCompilingFilter.addMappingForUrlPatterns(null, true, "/*");

}

From source file:guru.nidi.ramltester.RestTemplateTest.java

@Override
protected void init(Context ctx) {
    AnnotationConfigWebApplicationContext appCtx = new AnnotationConfigWebApplicationContext();
    appCtx.register(getClass());//from   w  w  w. j a  va 2 s. co  m
    DispatcherServlet dispatcher = new DispatcherServlet(appCtx);
    Tomcat.addServlet(ctx, "SpringMVC", dispatcher);
    ctx.addServletMapping("/*", "SpringMVC");
}

From source file:com.uimirror.auth.conf.WebAppInitializer.java

@Bean
public DispatcherServlet dispatcherServlet() {
    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(DispatcherConfig.class);
    return new DispatcherServlet(dispatcherContext);
}

From source file:test.org.spring.websocket.api.tomcat.support.TomcatWebSocketTestServer.java

public void deployConfig(WebApplicationContext cxt) {
    this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir"));
    this.context.addApplicationListener(WsContextListener.class.getName());
    Tomcat.addServlet(context, "dispatcherServlet", new DispatcherServlet(cxt));
    this.context.addServletMapping("/anyUrlPattern/*", "dispatcherServlet");
}

From source file:com.kixeye.chassis.support.test.eureka.ChassisEurekaTestConfiguration.java

@Order(0)
@Bean(initMethod = "start", destroyMethod = "stop")
public Server httpServer(@Value("${http.hostname}") String hostname, @Value("${http.port}") int port,
        ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(
            ServletContextHandler.NO_SESSIONS | ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);//from  w w w  .ja  v  a  2  s  .  c  o m
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

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

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = StringUtils.isBlank(hostname) ? new InetSocketAddress(port)
            : new InetSocketAddress(hostname, port);
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[] { connector });
    server.setHandler(servlets);

    return server;
}

From source file:com.dominion.salud.pedicom.configuration.PEDICOMInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.scan("com.dominion.salud.pedicom.configuration");
    ctx.setServletContext(servletContext);
    PEDICOMConstantes._NOMBRE_CONFIG = servletContext.getInitParameter("NOMBRE_CONFIG");
    System.setProperty("pedicom.conf.home", findConfigurationAndLogger(ctx));
    ctx.refresh();/*from   w  ww  .j  a  va 2  s  .  c o  m*/

    // Spring Dispatcher
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(ctx));
    dispatcher.setInitParameter("contextClass", ctx.getClass().getName());
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
    dispatcher.addMapping("/controller/*");
    servletContext.addListener(new ContextLoaderListener(ctx));

    // Configuracion general
    PEDICOMConstantes._HOME = StringUtils.endsWith(servletContext.getRealPath("/"), File.separator)
            ? servletContext.getRealPath("/")
            : servletContext.getRealPath("/") + File.separator;
    PEDICOMConstantes._CONF_HOME = ctx.getEnvironment().getProperty("pedicom.conf.home");
    PEDICOMConstantes._TEMP = PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "temp" + File.separator;
    PEDICOMConstantes._VERSION = ResourceBundle.getBundle("version").getString("version");
    PEDICOMConstantes._LOGS = PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "classes" + File.separator
            + "logs";
    PEDICOMConstantes._CONTEXT_NAME = servletContext.getServletContextName();
    PEDICOMConstantes._CONTEXT_PATH = servletContext.getContextPath();
    PEDICOMConstantes._CONTEXT_SERVER = servletContext.getServerInfo();
    PEDICOMConstantes._ENABLE_TECHNICAL_INFORMATION = StringUtils.isNotBlank(
            ResourceBundle.getBundle("application").getString("pedicom.enable.technical.information"))
                    ? Boolean.parseBoolean(ResourceBundle.getBundle("application")
                            .getString("pedicom.enable.technical.information"))
                    : false;
    PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = StringUtils
            .isNotBlank(ResourceBundle.getBundle("application").getString("pedicom_scheduler_send_mail_cron"))
                    ? PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = ResourceBundle.getBundle("application")
                            .getString("pedicom_scheduler_send_mail_cron")
                    : PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON;
    PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON = StringUtils.isNotBlank(
            ResourceBundle.getBundle("application").getString("pedicom_scheduler_update_existencias_cron"))
                    ? PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON = ResourceBundle.getBundle("application")
                            .getString("pedicom_scheduler_update_existencias_cron")
                    : PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON;

    // Configuracion de LOGS DEL MODULO
    if (StringUtils.isBlank(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())) {
        ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE"))
                .setFile(PEDICOMConstantes._HOME + "WEB-INF" + File.separator + "classes" + File.separator
                        + "logs" + File.separator + "mpr-desktop.log");
    }
    PEDICOMConstantes._LOGS = new File(
            ((FileAppender) org.apache.log4j.Logger.getRootLogger().getAppender("LOGFILE")).getFile())
                    .getParent();

    Environment env = ctx.getEnvironment();

    XmlUnmarshaler xml = new XmlUnmarshaler();
    Datos datos = (Datos) xml.unmarshal();
    logger.info("          Datasources");
    for (Datasources dat : datos.getDatasources()) {
        if (dat.getNombreDatasource().equals("Central")) {
            PEDICOMConstantes.EXISTENCIAS_EXISTE = true;
        }
        logger.info("               codCentro: " + dat.getCodCentro());
        logger.info("               nombreDatasource: " + dat.getNombreDatasource());
        logger.info("               driverClassName: " + dat.getDriverClassName());
        logger.info("               jndi: " + dat.getJndi());
        logger.info("               url: " + dat.getUrl());
        logger.info("               username: " + dat.getUsername());
        logger.info("               usernameEmail: " + dat.getUsernameEmail());
        logger.info("               passwordEmail: " + dat.getPasswordEmail());
        logger.info("               from: " + dat.getFrom());
        logger.info("               host: " + dat.getHost());
        logger.info("               port: " + dat.getPort());
        logger.info("               TLS: " + dat.getTLS());
        logger.info("               SSL: " + dat.getSSL());
    }
    //        ctx.refresh();
    //        PropertyConfigurator.configureAndWatch("log4j");

    logger.info("          Configuracion general del sistema");
    logger.info("               pedicom.home: " + PEDICOMConstantes._HOME);
    logger.info("               pedicom.conf.home: " + PEDICOMConstantes._CONF_HOME);
    logger.info("               pedicom.temp: " + PEDICOMConstantes._TEMP);
    logger.info("               pedicom.version: " + PEDICOMConstantes._VERSION);
    logger.info("               pedicom.logs: " + PEDICOMConstantes._LOGS);
    logger.info("               pedicom.context.name: " + PEDICOMConstantes._CONTEXT_NAME);
    logger.info("               pedicom.context.path: " + PEDICOMConstantes._CONTEXT_PATH);
    logger.info("               pedicom.context.server: " + PEDICOMConstantes._CONTEXT_SERVER);
    logger.info("          Parametrizacion del sistema");
    logger.info("               pedicom.enable.technical.information: "
            + PEDICOMConstantes._ENABLE_TECHNICAL_INFORMATION);
    logger.info(
            "               pedicom_scheduler_send_mail_cron: " + PEDICOMConstantes._SCHEDULER_SEND_MAIL_CRON);
    logger.info("               pedicom_scheduler_update_existencias_cron: "
            + PEDICOMConstantes._SCHEDULER_UPDATE_EXISTENCIAS_CRON);
    logger.info("     Modulo configurado correctamente");
    logger.info("MODULO INICIADO CORRECTAMENTE");
}

From source file:com.kixeye.chassis.bootstrap.webapp.TestSpringWebApp.java

@Bean(initMethod = "start", destroyMethod = "stop", name = "httpServer")
@Order(0)/*from ww w.j  a  v a  2 s  .  c  o m*/
public Server httpServer(ConfigurableWebApplicationContext webApplicationContext) {

    // set up servlets
    ServletHandler servlets = new ServletHandler();
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY);
    context.setErrorHandler(null);
    context.setWelcomeFiles(new String[] { "/" });

    // set up spring with the servlet context
    setServletContext(context.getServletContext());

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

    // map application servlets
    context.addServlet(new ServletHolder(dispatcher), "/");

    servlets.setHandler(context);

    // create the server
    InetSocketAddress address = new InetSocketAddress(SocketUtils.findAvailableTcpPort());

    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());
    server.setConnectors(new Connector[] { connector });
    server.setHandler(servlets);
    server.setStopAtShutdown(true);

    return server;
}

From source file:org.springsource.sinspctr.InspctrServer.java

@Override
public void afterPropertiesSet() throws IOException {
    this.scheduler.setPoolSize(3);
    this.scheduler.initialize();
    this.tomcat.setPort(this.port);
    Context tomcatContext = this.tomcat.addContext(this.contextPath,
            this.getClass().getClassLoader().getResources(".").nextElement().getFile());
    this.webApplicationContext.setServletContext(tomcatContext.getServletContext());
    this.webApplicationContext.refresh();

    DispatcherServlet servlet = new DispatcherServlet(this.webApplicationContext);
    servlet.setDispatchOptionsRequest(true);
    Tomcat.addServlet(tomcatContext, this.servletName, servlet);
    tomcatContext.addServletMapping("/", this.servletName);

    if (logger.isInfoEnabled()) {
        logger.info("initialized server: context=" + this.contextPath + ", servlet=" + this.servletName);
    }/*w ww  .  j  a  v  a 2s.  com*/
}

From source file:org.shaigor.rest.retro.config.WebAppInitializer.java

/**
 * Registers dispatcher servlet that will make MVC tick
 * @param servletContext to be used during creation and registration
 * @param rootContext web application context to be used during creation and registration
 *//* w w w .  j  a v  a  2  s . c o  m*/
private void configureSpringMvc(ServletContext servletContext, WebApplicationContext rootContext) {
    AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
    mvcContext.register(WordsSereviceConfig.class, InsecureWebMvcConfigurer.class);

    mvcContext.setParent(rootContext);

    ServletRegistration.Dynamic appServlet = servletContext.addServlet("webservice",
            new DispatcherServlet(mvcContext));
    appServlet.setLoadOnStartup(1);
    Set<String> mappingConflicts = appServlet.addMapping("/");

    if (!mappingConflicts.isEmpty()) {
        for (String s : mappingConflicts) {
            LOG.error("Mapping conflict: " + s);
        }
        throw new IllegalStateException("'webservice' cannot be mapped to '/'");
    }
}