下面列出了怎么用javax.servlet.ServletRegistration的API类实例代码及写法,或者点击链接到github查看源代码。
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());
}
}
@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/*");
}
/**
* 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);
}
@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;
}
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();
}
/**
* 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;
}
/**
* Test getClassName method.
*/
@Test
public void testGetClassName() {
webApp.addServlet("servlet", TestServlet.class);
ServletRegistration registration = webApp.getServletRegistration("servlet");
assertNotNull(TestServlet.class.getCanonicalName(), registration.getClassName());
}
@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 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");
}
@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);
}
@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("/");
}
@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(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);
}
/**
* 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");
}
@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");
}
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());
}
}
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());
});
}
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, "/*");
}
@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");
}
@Override
public ServletRegistration getServletRegistration(String servletName) {
Wrapper wrapper = (Wrapper) context.findChild(servletName);
if (wrapper == null) {
return null;
}
return new ApplicationServletRegistration(wrapper, context);
}
@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);
}
});
}
@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());
}