javax.servlet.ServletRegistration源码实例Demo

类javax.servlet.ServletRegistration源码实例Demo

下面列出了javax.servlet.ServletRegistration 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: seed   文件: ServletContextConfigurer.java
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());
    }
}
 
源代码2 项目: resteasy-examples   文件: MyWebAppInitializer.java
@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/*");
}
 
源代码3 项目: flow   文件: JSR356WebsocketInitializer.java
/**
 * 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);

}
 
源代码4 项目: layui-admin   文件: LayuiAdminStartUp.java
@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;
}
 
源代码5 项目: oxAuth   文件: ConfigurationFactory.java
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("\\*", "");
}
 
@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();
}
 
源代码7 项目: flowable-engine   文件: WebConfigurer.java
/**
 * 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;
}
 
源代码8 项目: piranha   文件: ServletRegistrationTest.java
/**
 * Test getClassName method.
 */
@Test
public void testGetClassName() {
    webApp.addServlet("servlet", TestServlet.class);
    ServletRegistration registration = webApp.getServletRegistration("servlet");
    assertNotNull(TestServlet.class.getCanonicalName(), registration.getClassName());
}
 
源代码9 项目: Tomcat7.0.67   文件: TestContextConfig.java
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    Servlet s = new CustomDefaultServlet();
    ServletRegistration.Dynamic r = ctx.addServlet(servletName, s);
    r.addMapping("/");
}
 
源代码10 项目: tomcatsrc   文件: ApplicationContext.java
@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;
}
 
@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");

}
 
源代码12 项目: syncope   文件: SyncopeBuildToolsApplication.java
@Override
public void onStartup(final ServletContext sc) throws ServletException {
    sc.addListener(new ConnectorServerStartStopListener());
    sc.addListener(new ApacheDSStartStopListener());
    sc.addListener(new H2StartStopListener());
    sc.addListener(new GreenMailStartStopListener());

    ServletRegistration.Dynamic apacheDS = sc.addServlet("ApacheDSRootDseServlet", ApacheDSRootDseServlet.class);
    apacheDS.addMapping("/apacheDS");
    ServletRegistration.Dynamic sts = sc.addServlet("ServiceTimeoutServlet", ServiceTimeoutServlet.class);
    sts.addMapping("/services/*");

    super.onStartup(sc);
}
 
源代码13 项目: tutorials   文件: WebAppInitializer.java
@Override
public void onStartup(ServletContext container) throws ServletException {
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	context.register(AppConfig.class);
	context.setServletContext(container);

	ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(context));
	servlet.setLoadOnStartup(1);
	servlet.addMapping("/");
}
 
源代码14 项目: tomcatsrc   文件: TestContextConfig.java
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    Servlet s = new CustomDefaultServlet();
    ServletRegistration.Dynamic r = ctx.addServlet(servletName, s);
    r.addMapping("/");
}
 
源代码15 项目: Tomcat7.0.67   文件: TestStandardContext.java
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    // Register and map servlet
    Servlet s = new Bug50015Servlet();
    ServletRegistration.Dynamic sr = ctx.addServlet("bug50015", s);
    sr.addMapping("/bug50015");

    // Limit access to users in the Tomcat role
    HttpConstraintElement hce = new HttpConstraintElement(
            TransportGuarantee.NONE, "tomcat");
    ServletSecurityElement sse = new ServletSecurityElement(hce);
    sr.setServletSecurity(sse);
}
 
源代码16 项目: wiztowar   文件: DWAdapter.java
/**
 * This method is adapted from ServerFactory.createInternalServlet.
 */
private void createInternalServlet(final ExtendedEnvironment env, final ServletContext context) {
    if (context.getMajorVersion() >= 3) {

        // Add the Task servlet
        final ServletRegistration.Dynamic taskServlet = context.addServlet("TaskServlet", new TaskServlet(env.getTasks()));
        taskServlet.setAsyncSupported(true);
        taskServlet.addMapping("/tasks/*");

        // Add the Admin servlet
        final ServletRegistration.Dynamic adminServlet = context.addServlet("AdminServlet", new AdminServlet());
        adminServlet.setAsyncSupported(true);
        adminServlet.addMapping("/admin/*");
    } else throw new IllegalStateException("The WizToWar adapter doesn't support servlet versions under 3");
}
 
源代码17 项目: Tomcat8-Source-Read   文件: TestContextConfig.java
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    Servlet s = new CustomDefaultServlet();
    ServletRegistration.Dynamic r = ctx.addServlet(servletName, s);
    r.addMapping("/");
}
 
@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");

}
 
源代码19 项目: Spring-5.0-Cookbook   文件: SpringWebinitializer.java
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);
  
 
     
}
 
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);
}
 
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());
    }
}
 
源代码22 项目: servicecomb-java-chassis   文件: ServletUtils.java
static List<ServletRegistration> findServletRegistrations(ServletContext servletContext,
    Class<?> servletCls) {
  return servletContext.getServletRegistrations()
      .values()
      .stream()
      .filter(predicate -> predicate.getClassName().equals(servletCls.getName()))
      .collect(Collectors.toList());
}
 
@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());
			});
}
 
源代码24 项目: flow   文件: ServletDeployer.java
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, "/*");
}
 
源代码25 项目: tomcatsrc   文件: ApplicationContextFacade.java
@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);
    }
}
 
@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");

}
 
源代码27 项目: Tomcat7.0.67   文件: ApplicationContext.java
@Override
public ServletRegistration getServletRegistration(String servletName) {
    Wrapper wrapper = (Wrapper) context.findChild(servletName);
    if (wrapper == null) {
        return null;
    }

    return new ApplicationServletRegistration(wrapper, context);
}
 
源代码28 项目: airpal   文件: AirpalApplicationBase.java
@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);
        }
    });
}
 
源代码29 项目: lams   文件: ServletContextImpl.java
@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);
}
 
/**
 * @since 4.1.2
 */
@Test
public void getServletRegistrations() {
	Map<String, ? extends ServletRegistration> servletRegistrations = sc.getServletRegistrations();
	assertNotNull(servletRegistrations);
	assertEquals(0, servletRegistrations.size());
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法