javax.servlet.ServletRegistration Java Examples

The following examples show how to use javax.servlet.ServletRegistration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConfigurationFactory.java    From oxAuth with MIT License 6 votes vote down vote up
public void onServletContextActivation(@Observes ServletContext context ) {
   this.contextPath = context.getContextPath();

   this.facesMapping = "";
   ServletRegistration servletRegistration = context.getServletRegistration("Faces Servlet");
   if (servletRegistration == null) {
   	return;
   }

   String[] mappings = servletRegistration.getMappings().toArray(new String[0]);
   if (mappings.length == 0) {
       return;
   }
   
   this.facesMapping = mappings[0].replaceAll("\\*", "");
}
 
Example #2
Source File: ServletContextConfigurer.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
void addServlet(ServletDefinition servletDefinition) {
    ServletRegistration.Dynamic servletRegistration = servletContext.addServlet(
            servletDefinition.getName(),
            injector.getInstance(servletDefinition.getServletClass())
    );

    if (servletRegistration != null) {
        servletRegistration.setAsyncSupported(servletDefinition.isAsyncSupported());
        for (String mapping : servletDefinition.getMappings()) {
            servletRegistration.addMapping(mapping);
        }
        servletRegistration.setLoadOnStartup(servletDefinition.getLoadOnStartup());
        servletRegistration.setInitParameters(servletDefinition.getInitParameters());
    } else {
        LOGGER.warn(
                "Servlet {} was already registered by the container: injection and interception are not available"
                        + ". Consider adding a web.xml file with metadata-complete=true.",
                servletDefinition.getName());
    }
}
 
Example #3
Source File: MyWebAppInitializer.java    From resteasy-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    // `ResteasyBootstrap` is not mandatory if you want to setup `ResteasyContext` and `ResteasyDeployment` manually.
    servletContext.addListener(ResteasyBootstrap.class);

    // Create Spring context.
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(MyConfig.class);

    // Implement our own `ContextLoaderListener`, so we can implement our own `SpringBeanProcessor` if necessary.
    servletContext.addListener(new MyContextLoaderListener(context));

    // We can use `HttpServletDispatcher` or `FilterDispatcher` here, and implement our own solution.
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("resteasy-dispatcher", new HttpServletDispatcher());
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/rest/*");
}
 
Example #4
Source File: WebConfigurer.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes Spring and Spring MVC.
 */
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
    LOGGER.debug("Configuring Spring Web application context");
    AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
    dispatcherServletConfiguration.setParent(rootContext);
    dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);

    LOGGER.debug("Registering Spring MVC Servlet");
    ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
    dispatcherServlet.addMapping("/service/*");
    dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
    dispatcherServlet.setLoadOnStartup(1);
    dispatcherServlet.setAsyncSupported(true);

    return dispatcherServlet;
}
 
Example #5
Source File: TestServletUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSaveUrlPrefixNormal(@Mocked ServletContext servletContext,
    @Mocked ServletRegistration servletRegistration) {
  ClassLoaderScopeContext.clearClassLoaderScopeProperty();
  new Expectations() {
    {
      servletContext.getContextPath();
      result = "/root";
      servletRegistration.getClassName();
      result = RestServlet.class.getName();
      servletRegistration.getMappings();
      result = Arrays.asList("/rest/*");
      servletContext.getServletRegistrations();
      result = Collections.singletonMap("test", servletRegistration);
    }
  };

  ServletUtils.saveUrlPrefix(servletContext);

  Assert.assertThat(ClassLoaderScopeContext.getClassLoaderScopeProperty(DefinitionConst.URL_PREFIX),
      Matchers.is("/root/rest"));
  ClassLoaderScopeContext.clearClassLoaderScopeProperty();
}
 
Example #6
Source File: LayuiAdminStartUp.java    From layui-admin with MIT License 6 votes vote down vote up
@Bean
public ServletWebServerFactory servletContainer() {
    TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
    tomcat.addInitializers(new ServletContextInitializer(){
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            XmlWebApplicationContext context = new XmlWebApplicationContext();
            context.setConfigLocations(new String[]{"classpath:applicationContext-springmvc.xml"});
            DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
            ServletRegistration.Dynamic dispatcher = servletContext
                    .addServlet("dispatcher", dispatcherServlet);

            dispatcher.setLoadOnStartup(1);
            dispatcher.addMapping("/");
        }
    });
    tomcat.setContextPath("/manager");
    tomcat.addTldSkipPatterns("xercesImpl.jar","xml-apis.jar","serializer.jar");
    tomcat.setPort(port);

    return tomcat;
}
 
Example #7
Source File: JSR356WebsocketInitializer.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes Atmosphere for use with the given Vaadin servlet
 * <p>
 * For JSR 356 websockets to work properly, the initialization must be done
 * in the servlet context initialization phase.
 *
 * @param servletRegistration
 *            The servlet registration info for the servlet
 * @param servletContext
 *            The servlet context
 */
public static void initAtmosphereForVaadinServlet(
        ServletRegistration servletRegistration,
        ServletContext servletContext) {
    getLogger().debug("Initializing Atmosphere for Vaadin Servlet: {}",
            servletRegistration.getName());
    String servletName = servletRegistration.getName();
    String attributeName = getAttributeName(servletName);

    if (servletContext.getAttribute(attributeName) != null) {
        // Already initialized
        getLogger().warn("Atmosphere already initialized");
        return;
    }
    getLogger().debug("Creating AtmosphereFramework for {}", servletName);
    AtmosphereFramework framework = PushRequestHandler.initAtmosphere(
            new FakeServletConfig(servletRegistration, servletContext));
    servletContext.setAttribute(attributeName, framework);
    getLogger().debug("Created AtmosphereFramework for {}", servletName);

}
 
Example #8
Source File: TestContextConfig.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    Servlet s = new CustomDefaultServlet();
    ServletRegistration.Dynamic r = ctx.addServlet(servletName, s);
    r.addMapping("/");
}
 
Example #9
Source File: AnnotationConfigDispatcherServletInitializerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
	if (servlets.containsKey(servletName)) {
		return null;
	}
	servlets.put(servletName, servlet);
	MockServletRegistration registration = new MockServletRegistration();
	servletRegistrations.put(servletName, registration);
	return registration;
}
 
Example #10
Source File: WebAppInitializer.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void onStartup(final ServletContext servletContext)
        throws ServletException {

    // Register DispatcherServlet
    super.onStartup(servletContext);

    // Register H2 Admin console:
    ServletRegistration.Dynamic h2WebServlet = servletContext.addServlet("h2WebServlet",
            "org.h2.server.web.WebServlet");
    h2WebServlet.addMapping("/admin/h2/*");
    h2WebServlet.setInitParameter("webAllowOthers", "true");

}
 
Example #11
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public ServletRegistration getServletRegistration(final String servletName) {
    ensureNotProgramaticListener();
    final ManagedServlet servlet = deployment.getServlets().getManagedServlet(servletName);
    if (servlet == null) {
        return null;
    }
    return new ServletRegistrationImpl(servlet.getServletInfo(), servlet, deployment);
}
 
Example #12
Source File: WebAppInitializer.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void onStartup(final ServletContext servletContext)
        throws ServletException {

    // Register DispatcherServlet
    super.onStartup(servletContext);

    // Register H2 Admin console:
    ServletRegistration.Dynamic h2WebServlet = servletContext.addServlet("h2WebServlet",
            "org.h2.server.web.WebServlet");
    h2WebServlet.addMapping("/admin/h2/*");
    h2WebServlet.setInitParameter("webAllowOthers", "true");

}
 
Example #13
Source File: AirpalApplicationBase.java    From airpal with Apache License 2.0 5 votes vote down vote up
@Override
public void run(T config, Environment environment)
        throws Exception
{
    this.injector = Guice.createInjector(Stage.PRODUCTION, getModules(config, environment));

    System.setProperty(IO_BUFFER_SIZE, String.valueOf(config.getBufferSize().toBytes()));

    environment.healthChecks().register("presto", injector.getInstance(PrestoHealthCheck.class));

    environment.jersey().register(injector.getInstance(ExecuteResource.class));
    environment.jersey().register(injector.getInstance(QueryResource.class));
    environment.jersey().register(injector.getInstance(QueriesResource.class));
    environment.jersey().register(injector.getInstance(UserResource.class));
    environment.jersey().register(injector.getInstance(UsersResource.class));
    environment.jersey().register(injector.getInstance(TablesResource.class));
    environment.jersey().register(injector.getInstance(HealthResource.class));
    environment.jersey().register(injector.getInstance(PingResource.class));
    environment.jersey().register(injector.getInstance(SessionResource.class));
    environment.jersey().register(injector.getInstance(FilesResource.class));
    environment.jersey().register(injector.getInstance(ResultsPreviewResource.class));
    environment.jersey().register(injector.getInstance(S3FilesResource.class));

    environment.jersey().register(injector.getInstance(AirpalUserFactory.class));

    // Setup SSE (Server Sent Events)
    ServletRegistration.Dynamic sseServlet = environment.servlets()
            .addServlet("updates", injector.getInstance(SSEEventSourceServlet.class));
    sseServlet.setAsyncSupported(true);
    sseServlet.addMapping("/api/updates/subscribe");

    // Disable GZIP content encoding for SSE endpoints
    environment.lifecycle().addServerLifecycleListener(server -> {
        for (Handler handler : server.getChildHandlersByClass(BiDiGzipHandler.class)) {
            ((BiDiGzipHandler) handler).addExcludedMimeTypes(SERVER_SENT_EVENTS);
        }
    });
}
 
Example #14
Source File: WebAppInitializer.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public void onStartup(final ServletContext servletContext)
        throws ServletException {

    // Register DispatcherServlet
    super.onStartup(servletContext);

    // Register H2 Admin console:
    ServletRegistration.Dynamic h2WebServlet = servletContext.addServlet("h2WebServlet",
            "org.h2.server.web.WebServlet");
    h2WebServlet.addMapping("/admin/h2/*");
    h2WebServlet.setInitParameter("webAllowOthers", "true");

}
 
Example #15
Source File: ApplicationContext.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, ? extends ServletRegistration> getServletRegistrations() {
    Map<String, ApplicationServletRegistration> result =
        new HashMap<String, ApplicationServletRegistration>();

    Container[] wrappers = context.findChildren();
    for (Container wrapper : wrappers) {
        result.put(((Wrapper) wrapper).getName(),
                new ApplicationServletRegistration(
                        (Wrapper) wrapper, context));
    }

    return result;
}
 
Example #16
Source File: MockServletContextTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * @since 4.1.2
 */
@Test
public void getServletRegistrations() {
	Map<String, ? extends ServletRegistration> servletRegistrations = sc.getServletRegistrations();
	assertNotNull(servletRegistrations);
	assertEquals(0, servletRegistrations.size());
}
 
Example #17
Source File: WebXmlInitializerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test onStartup method.
 *
 * @throws Exception when a serious error occurs.
 */
@Test
public void testOnStartup() throws Exception {
    DefaultWebApplication webApplication = new DefaultWebApplication();
    webApplication.addResource(new DirectoryResource(new File("src/test/webxml/init")));
    webApplication.addInitializer(new WebXmlInitializer());
    webApplication.initialize();
    ServletRegistration registration = webApplication.getServletRegistration("Test Servlet");
    assertNotNull(registration);
    assertFalse(registration.getMappings().isEmpty());
    assertEquals("*.html", registration.getMappings().iterator().next());
    assertEquals("application/x-java-class", webApplication.getMimeType("my.class"));
    assertEquals("myvalue", webApplication.getInitParameter("myname"));
    assertEquals("myservletcontext", webApplication.getServletContextName());
}
 
Example #18
Source File: ServletRegistrationTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Test getClassName method.
 */
@Test
public void testGetClassName() {
    webApp.addServlet("servlet", TestServlet.class);
    ServletRegistration registration = webApp.getServletRegistration("servlet");
    assertNotNull(TestServlet.class.getCanonicalName(), registration.getClassName());
}
 
Example #19
Source File: ApplicationContextFacade.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked") // doPrivileged() returns the correct type
public Map<String, ? extends ServletRegistration> getServletRegistrations() {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (Map<String, ? extends ServletRegistration>) doPrivileged(
                "getServletRegistrations", null);
    } else {
        return context.getServletRegistrations();
    }
}
 
Example #20
Source File: ServletContextImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public ServletRegistration getServletRegistration(final String servletName) {
    ensureNotProgramaticListener();
    final ManagedServlet servlet = deployment.getServlets().getManagedServlet(servletName);
    if (servlet == null) {
        return null;
    }
    return new ServletRegistrationImpl(servlet.getServletInfo(), servlet, deployment);
}
 
Example #21
Source File: SpringWebinitializer.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 
	 
  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch06-servlet", 
  		new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("/");
  dispatcher.setLoadOnStartup(1);
  
 
     
}
 
Example #22
Source File: AssetsBundleTest.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 5 votes vote down vote up
private void runBundle(ConfiguredAssetsBundle bundle, String assetName,
                       AssetsBundleConfiguration config) throws Exception {
  final ServletRegistration.Dynamic registration = mock(ServletRegistration.Dynamic.class);
  when(servletEnvironment.addServlet(anyString(), any(AssetServlet.class)))
          .thenReturn(registration);

  bundle.run(config, environment);

  final ArgumentCaptor<AssetServlet> servletCaptor = ArgumentCaptor.forClass(AssetServlet.class);
  final ArgumentCaptor<String> pathCaptor = ArgumentCaptor.forClass(String.class);

  verify(servletEnvironment, atLeastOnce()).addServlet(eq(assetName), servletCaptor.capture());
  verify(registration, atLeastOnce()).addMapping(pathCaptor.capture());

  this.servletPath = pathCaptor.getValue();
  this.servletPaths = pathCaptor.getAllValues();

  // If more than one servlet was captured, let's verify they're the same instance.
  List<AssetServlet> capturedServlets = servletCaptor.getAllValues();
  if (capturedServlets.size() > 1) {
    for (AssetServlet servlet : capturedServlets) {
      assertThat(servlet == capturedServlets.get(0));
    }
  }

  this.servlet = capturedServlets.get(0);
}
 
Example #23
Source File: RegisterPrecompiledJSPInitializer.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
private static void registerPrecompiledJSPs(ServletContext servletContext) {
    WebApp webApp = parseXmlFragment();
    for (ServletDef def : webApp.getServletDefs()) {
        LOG.trace("Registering precompiled JSP: {} -> {}", def.getName(), def.getSclass());
        ServletRegistration.Dynamic reg = servletContext.addServlet(def.getName(), def.getSclass());
        // Need to set loadOnStartup somewhere between 0 and 128. 0 is highest priority. 99 should be fine
        reg.setLoadOnStartup(99);
    }

    for (ServletMappingDef mapping : webApp.getServletMappingDefs()) {
        LOG.trace("Mapping servlet: {} -> {}", mapping.getName(), mapping.getUrlPattern());
        servletContext.getServletRegistration(mapping.getName()).addMapping(mapping.getUrlPattern());
    }
}
 
Example #24
Source File: ServletUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
static List<ServletRegistration> findServletRegistrations(ServletContext servletContext,
    Class<?> servletCls) {
  return servletContext.getServletRegistrations()
      .values()
      .stream()
      .filter(predicate -> predicate.getClassName().equals(servletCls.getName()))
      .collect(Collectors.toList());
}
 
Example #25
Source File: BootstrapUtil.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
private static void buildServletRegistrationMessage(StringBuilder builder, String servletId, ServletRegistration registration) {
	builder.append(NEW_LINE).append(VALUE_PREFIX).append(servletId).append(VALUE_SEPARATOR);
	builder.append(NEW_LINE).append(SUB_VALUE_PREFIX).append("Name.......: ").append(registration.getName());
	builder.append(NEW_LINE).append(SUB_VALUE_PREFIX).append("Class name.: ").append(registration.getClassName());
	addRunAsRole(builder, registration.getRunAsRole());
	addInitParameters(builder, registration.getInitParameters());
	addMappings(builder, registration.getMappings());
}
 
Example #26
Source File: JPAWebConfigurer.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes Spring and Spring MVC.
 */
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
  log.debug("Configuring Spring Web application context");
  AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
  dispatcherServletConfiguration.setParent(rootContext);
  dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);

  log.debug("Registering Spring MVC Servlet");
  ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
  dispatcherServlet.addMapping("/service/*");
  dispatcherServlet.setLoadOnStartup(1);
  dispatcherServlet.setAsyncSupported(true);

  return dispatcherServlet;
}
 
Example #27
Source File: ApplicationContextFacade.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public ServletRegistration.Dynamic addServlet(String servletName,
        Class<? extends Servlet> servletClass) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return (ServletRegistration.Dynamic) doPrivileged("addServlet",
                new Class[]{String.class, Class.class},
                new Object[]{servletName, servletClass});
    } else {
        return context.addServlet(servletName, servletClass);
    }
}
 
Example #28
Source File: FacesServletAutoConfigurationTest.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
public void testServletContextAttributes_added() {
	this.webApplicationContextRunner
			.run(context -> {
				ServletRegistrationBean<FacesServlet> facesServletRegistrationBean = (ServletRegistrationBean<FacesServlet>) context.getBean("facesServletRegistrationBean");

				ServletContext servletContext = mock(ServletContext.class);

				when(servletContext.addServlet(anyString(), any(Servlet.class))).thenReturn(mock(ServletRegistration.Dynamic.class));

				facesServletRegistrationBean.onStartup(servletContext);

				verify(servletContext, times(2)).setAttribute(any(), any());
			});
}
 
Example #29
Source File: ContainerListener.java    From smart-framework with Apache License 2.0 5 votes vote down vote up
private void registerJspServlet(ServletContext context) {
    ServletRegistration jspServlet = context.getServletRegistration("jsp");
    jspServlet.addMapping("/index.jsp");
    String jspPath = FrameworkConstant.JSP_PATH;
    if (StringUtil.isNotEmpty(jspPath)) {
        jspServlet.addMapping(jspPath + "*");
    }
}
 
Example #30
Source File: ServletDeployer.java    From flow with Apache License 2.0 5 votes vote down vote up
private VaadinServletCreation createAppServlet(
        ServletContext servletContext) {
    VaadinServletContext context = new VaadinServletContext(servletContext);
    boolean createServlet = ApplicationRouteRegistry.getInstance(context)
            .hasNavigationTargets();

    createServlet = createServlet || WebComponentConfigurationRegistry
            .getInstance(context).hasConfigurations();

    if (!createServlet) {
        servletCreationMessage = String.format(
                "%s there are no navigation targets registered to the "
                        + "route registry and there are no web component exporters.",
                SKIPPING_AUTOMATIC_SERVLET_REGISTRATION_BECAUSE);
        return VaadinServletCreation.NO_CREATION;
    }

    ServletRegistration vaadinServlet = findVaadinServlet(servletContext);
    if (vaadinServlet != null) {
        servletCreationMessage = String.format(
                "%s there is already a Vaadin servlet with the name %s",
                SKIPPING_AUTOMATIC_SERVLET_REGISTRATION_BECAUSE,
                vaadinServlet.getName());
        return VaadinServletCreation.SERVLET_EXISTS;
    }

    return createServletIfNotExists(servletContext, getClass().getName(),
            VaadinServlet.class, "/*");
}