org.apache.catalina.startup.Tomcat类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(16.3k)|赞(0)|评价(0)|浏览(150)

本文整理了Java中org.apache.catalina.startup.Tomcat类的一些代码示例,展示了Tomcat类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Tomcat类的具体详情如下:
包路径:org.apache.catalina.startup.Tomcat
类名称:Tomcat

Tomcat介绍

[英]Minimal tomcat starter for embedding/unit tests. Tomcat supports multiple styles of configuration and startup - the most common and stable is server.xml-based, implemented in org.apache.catalina.startup.Bootstrap. This class is for use in apps that embed tomcat. Requirements: - all tomcat classes and possibly servlets are in the classpath. ( for example all is in one big jar, or in eclipse CP, or in any other combination ) - we need one temporary directory for work files - no config file is required. This class provides methods to use if you have a webapp with a web.xml file, but it is optional - you can use your own servlets. There are a variety of 'add' methods to configure servlets and webapps. These methods, by default, create a simple in-memory security realm and apply it. If you need more complex security processing, you can define a subclass of this class. This class provides a set of convenience methods for configuring webapp contexts, all overloads of the method addWebapp. These methods create a webapp context, configure it, and then add it to a Host. They do not use a global default web.xml; rather, they add a lifecycle listener that adds the standard DefaultServlet, JSP processing, and welcome files. In complex cases, you may prefer to use the ordinary Tomcat API to create webapp contexts; for example, you might need to install a custom Loader before the call to Host#addChild(Container). To replicate the basic behavior of the addWebapp methods, you may want to call two methods of this class: #noDefaultWebXmlPath() and #getDefaultWebXmlListener(). #getDefaultWebXmlListener() returns a LifecycleListener that adds the standard DefaultServlet, JSP processing, and welcome files. If you add this listener, you must prevent Tomcat from applying any standard global web.xml with ... #noDefaultWebXmlPath() returns a dummy pathname to configure to prevent ContextConfig from trying to apply a global web.xml file. This class provides a main() and few simple CLI arguments, see setters for doc. It can be used for simple tests and demo.
[中]用于嵌入/单元测试的最小tomcat启动器。Tomcat支持多种配置和启动方式——最常见、最稳定的是服务器。基于xml,在组织中实现。阿帕奇。卡塔琳娜。创业。独自创立此类用于嵌入tomcat的应用程序。要求:-所有tomcat类和可能的servlet都在类路径中。(例如,所有文件都在一个大罐子中,或者在eclipse CP中,或者在任何其他组合中)——我们需要一个临时目录来存放工作文件——不需要配置文件。如果您有一个带有web应用程序的webapp,则此类提供了要使用的方法。xml文件,但它是可选的——您可以使用自己的servlet。有多种“添加”方法来配置servlet和webapps。默认情况下,这些方法创建一个简单的内存安全域并应用它。如果需要更复杂的安全处理,可以定义此类的子类。这个类提供了一组方便的方法来配置webapp上下文,方法addWebapp的所有重载。这些方法创建webapp上下文,对其进行配置,然后将其添加到主机。它们不使用全局默认web。xml;相反,他们添加了一个生命周期监听器,该监听器添加了标准的DefaultServlet、JSP处理和欢迎文件。在复杂的情况下,您可能更喜欢使用普通的Tomcat API来创建webapp上下文;例如,在调用Host#addChild(Container)之前,您可能需要安装一个自定义加载程序。要复制addWebapp方法的基本行为,您可能需要调用此类的两个方法:#noDefaultWebXmlPath()和#getDefaultWebXmlListener()#getDefaultWebXmlListener()返回一个LifecycleListener,它添加标准的DefaultServlet、JSP处理和欢迎文件。如果添加此侦听器,则必须防止Tomcat应用任何标准的全局web。xml与#noDefaultWebXmlPath()返回一个要配置的虚拟路径名,以防止ContextConfig尝试应用全局web。xml文件。这个类提供了一个main()和几个简单的CLI参数,请参见doc的setters。它可以用于简单的测试和演示。

代码示例

代码示例来源:origin: stackoverflow.com

String webappDirLocation = "src/main/webapp/";
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);

StandardContext ctx = (StandardContext) tomcat.addWebapp("/embeddedTomcat",
        new File(webappDirLocation).getAbsolutePath());

//declare an alternate location for your "WEB-INF/classes" dir:     
File additionWebInfClasses = new File("target/classes");
VirtualDirContext resources = new VirtualDirContext();
resources.setExtraResourcePaths("/WEB-INF/classes=" + additionWebInfClasses);
ctx.setResources(resources);

tomcat.start();
tomcat.getServer().await();

代码示例来源:origin: apache/incubator-dubbo

DispatcherServlet.addHttpHandler(url.getPort(), handler);
String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
tomcat = new Tomcat();
tomcat.setBaseDir(baseDir);
tomcat.setPort(url.getPort());
tomcat.getConnector().setProperty(
    "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)));
tomcat.getConnector().setProperty(
    "maxConnections", String.valueOf(url.getParameter(Constants.ACCEPTS_KEY, -1)));
tomcat.getConnector().setProperty("URIEncoding", "UTF-8");
tomcat.getConnector().setProperty("connectionTimeout", "60000");
tomcat.getConnector().setProperty("maxKeepAliveRequests", "-1");
tomcat.getConnector().setProtocol("org.apache.coyote.http11.Http11NioProtocol");
Context context = tomcat.addContext("/", baseDir);
Tomcat.addServlet(context, "dispatcher", new DispatcherServlet());
context.addServletMapping("/*", "dispatcher");
ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext());
  tomcat.start();
} catch (LifecycleException e) {
  throw new IllegalStateException("Failed to start tomcat server at " + url.getAddress(), e);

代码示例来源:origin: SonarSource/sonarqube

void terminate() {
 if (tomcat.getServer().getState().isAvailable()) {
  try {
   tomcat.stop();
   tomcat.destroy();
  } catch (Exception e) {
   Loggers.get(EmbeddedTomcat.class).error("Fail to stop web server", e);
  }
 }
 deleteQuietly(tomcatBasedir());
}

代码示例来源:origin: spring-projects/spring-framework

@Override
protected void stopInternal() throws Exception {
  this.tomcatServer.stop();
  this.tomcatServer.destroy();
}

代码示例来源:origin: OryxProject/oryx

private void configureTomcat(Tomcat tomcat, Connector connector) {
 tomcat.setBaseDir(noSuchBaseDir.toAbsolutePath().toString());
 tomcat.setConnector(connector);
}

代码示例来源:origin: org.visallo/visallo-tomcat-server

ProtocolHandler handler = httpsConnector.getProtocolHandler();
if (handler instanceof AbstractHttp11Protocol) {
  AbstractHttp11Protocol protocol = (AbstractHttp11Protocol) handler;
tomcat = new Tomcat();
tomcat.setPort(super.getHttpPort());
Connector defaultConnector = tomcat.getConnector();
defaultConnector.setRedirectPort(super.getHttpsPort());
tomcat.getService().addConnector(httpsConnector);
Context context = tomcat.addWebapp(this.getContextPath(), getWebAppDir().getAbsolutePath());
context.setJarScanner(jarScanner);
webRoot.setCacheMaxSize(100000);
webRoot.setCachingAllowed(true);
context.setResources(webRoot);
LOGGER.info("getSessionTimeout() is %d minutes", context.getSessionTimeout());
tomcat.start();
tomcat.getServer().await();

代码示例来源:origin: AsyncHttpClient/async-http-client

tomcat = new Tomcat();
tomcat.setHostname("localhost");
tomcat.setPort(0);
tomcat.setBaseDir(path);
Context ctx = tomcat.addContext("", path);
Tomcat.addServlet(ctx, "webdav", new WebdavServlet() {
 @Override
 public void init(ServletConfig config) throws ServletException {
ctx.addServletMappingDecoded("/*", "webdav");
tomcat.start();
port1 = tomcat.getConnector().getLocalPort();

代码示例来源:origin: codefollower/Tomcat-Research

/**
 * Get the default http connector. You can set more
 * parameters - the port is already initialized.
 *
 * Alternatively, you can construct a Connector and set any params,
 * then call addConnector(Connector)
 *
 * @return A connector object that can be customized
 */
public Connector getConnector() {
  getServer();
  if (connector != null) {
    return connector;
  }
  // This will load Apr connector if available,
  // default to nio. I'm having strange problems with apr
  // XXX: jfclere weird... Don't add the AprLifecycleListener then.
  // and for the use case the speed benefit wouldn't matter.
  connector = new Connector("HTTP/1.1");
  // connector = new Connector("org.apache.coyote.http11.Http11Protocol");
  connector.setPort(port);
  service.addConnector( connector );
  return connector;
}

代码示例来源:origin: nutzam/nutzboot

@Override
public void init() throws LifecycleException {
  this.tomcat = new Tomcat();
  File baseDir = createTempDir("tomcat");
  this.tomcat.setBaseDir(baseDir.getAbsolutePath());
  Connector connector = new Connector(PROP_PROTOCOL);
  connector.setPort(getPort());
  connector.setURIEncoding(DEFAULT_CHARSET.name());
  connector.setMaxPostSize(conf.getInt(PROP_MAX_POST_SIZE, 64 * 1024 * 1024));
  String connectorKey = PRE + "connector.";
  for (String key : conf.keys()) {
    if (key.startsWith(connectorKey)) {
      String k = key.substring(connectorKey.length());
      String v = conf.get(key);
      connector.setProperty(k, v);
    }
  }
  // 设置一下最大线程数
  this.tomcat.getService().addConnector(connector);
  StandardThreadExecutor executor = new StandardThreadExecutor();
  executor.setMaxThreads(getMaxThread());
  connector.getService().addExecutor(executor);
  this.tomcat.setConnector(connector);
  this.tomcat.setHostname(getHost());
  this.tomcat.getHost().setAutoDeploy(false);
  this.tomcat.getEngine().setBackgroundProcessorDelay(30);
  this.prepareContext();
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void setup() {
  Connector connector = new Connector(Http11NioProtocol.class.getName());
  connector.setPort(0);
  File baseDir = createTempDir("tomcat");
  String baseDirPath = baseDir.getAbsolutePath();
  this.tomcatServer = new Tomcat();
  this.tomcatServer.setBaseDir(baseDirPath);
  this.tomcatServer.setPort(0);
  this.tomcatServer.getService().addConnector(connector);
  this.tomcatServer.setConnector(connector);
}

代码示例来源:origin: com.att.nsa/nsaServerLibrary

this.name = builder.name();
tomcat = new Tomcat();
final Context rootCtx = tomcat.addContext("", makeTmpDir(name + "Context").getAbsolutePath());
Tomcat.addServlet(rootCtx, servletName, servlet);
rootCtx.addServletMapping ( "/*", servletName);
  for (ApiServerConnector connector : userConnectors ) {
    final Connector conn = new Connector ( builder.protocolClassName );
    if ( connector.isSecure () )
      conn.setScheme ( "https" );
      conn.setSecure ( true );
      conn.setAttribute ( "keystorePass", connector.keystorePassword () );
      conn.setAttribute ( "keystoreFile", connector.keystoreFile () );
    if (connector.maxThreads() > 0) conn.setAttribute("maxThreads", connector.maxThreads());
    tomcat.getService().addConnector(conn);
    if ( !doneOne )
      tomcat.setConnector ( conn );

代码示例来源:origin: apache/tapestry-5

public TomcatRunner(String webappFolder, String contextPath, int port, int sslPort) throws Exception
{
  this.port = port;
  this.sslPort = sslPort;
  final String expandedPath = expand(webappFolder);
  description = String.format("<TomcatRunner:%s:%s/%s (%s)", contextPath, port, sslPort, expandedPath);
  tomcatServer = new Tomcat();
  // Tomcat creates a folder, try to put it in an OS agnostic tmp dir
  String tmpDir = System.getProperty("java.io.tmpdir");
  String fileSeparator = System.getProperty("file.separator");
  if (!tmpDir.endsWith(fileSeparator))
    tmpDir = tmpDir + fileSeparator;
  tomcatServer.setBaseDir(tmpDir + "tomcat");
  tomcatServer.addWebapp("/", expandedPath);
  tomcatServer.getConnector().setAllowTrace(true);
  // SSL support
  final File keystoreFile = new File(TapestryRunnerConstants.MODULE_BASE_DIR, "src/test/conf/keystore");
  if (keystoreFile.exists())
  {
    final Connector https = new Connector();
    https.setPort(sslPort);
    https.setProperty("keystore", keystoreFile.getPath());
    https.setProperty("keypass", "tapestry");
    tomcatServer.getService().addConnector(https);
  }
  tomcatServer.start();
}

代码示例来源:origin: org.springframework.boot/spring-boot

@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
  Tomcat tomcat = new Tomcat();
  File baseDir = (this.baseDirectory != null) ? this.baseDirectory
      : createTempDir("tomcat");
  tomcat.setBaseDir(baseDir.getAbsolutePath());
  Connector connector = new Connector(this.protocol);
  tomcat.getService().addConnector(connector);
  customizeConnector(connector);
  tomcat.setConnector(connector);
  tomcat.getHost().setAutoDeploy(false);
  configureEngine(tomcat.getEngine());
  for (Connector additionalConnector : this.additionalTomcatConnectors) {
    tomcat.getService().addConnector(additionalConnector);
  }
  prepareContext(tomcat.getHost(), initializers);
  return getTomcatWebServer(tomcat);
}

代码示例来源:origin: apache/usergrid

public static void main(String[] args) throws Exception {
  String webappsPath = args[0];
  int port = Integer.parseInt( args[1] );
  File dataDir = Files.createTempDir();
  dataDir.deleteOnExit();
  Tomcat tomcat = new Tomcat();
  tomcat.setBaseDir(dataDir.getAbsolutePath());
  tomcat.setPort(port);
  tomcat.getConnector().setAttribute("maxThreads", "1000");
  tomcat.addWebapp("/", new File(webappsPath).getAbsolutePath());
  logger.info("-----------------------------------------------------------------");
  logger.info("Starting Tomcat port {} dir {}", port, webappsPath);
  logger.info("-----------------------------------------------------------------");
  tomcat.start();
  while ( true ) {
    Thread.sleep(1000);
  }
}

代码示例来源:origin: line/armeria

@Override
  protected void configure(ServerBuilder sb) throws Exception {
    // Prepare Tomcat instances.
    tomcatWithWebApp = new Tomcat();
    tomcatWithWebApp.setPort(0);
    tomcatWithWebApp.setBaseDir("build" + File.separatorChar +
                  "tomcat-" + UnmanagedTomcatServiceTest.class.getSimpleName() + "-1");
    tomcatWithWebApp.addWebapp("", WebAppContainerTest.webAppRoot().getAbsolutePath());
    TomcatUtil.engine(tomcatWithWebApp.getService(), "foo").setName("tomcatWithWebApp");
    tomcatWithoutWebApp = new Tomcat();
    tomcatWithoutWebApp.setPort(0);
    tomcatWithoutWebApp.setBaseDir("build" + File.separatorChar +
                    "tomcat-" + UnmanagedTomcatServiceTest.class.getSimpleName() + "-2");
    assertThat(TomcatUtil.engine(tomcatWithoutWebApp.getService(), "bar")).isNotNull();
    // Start the Tomcats.
    tomcatWithWebApp.start();
    tomcatWithoutWebApp.start();
    // Bind them to the Server.
    sb.serviceUnder("/empty/", TomcatService.forConnector("someHost", new Connector()))
     .serviceUnder("/some-webapp-nohostname/",
            TomcatService.forConnector(tomcatWithWebApp.getConnector()))
     .serviceUnder("/no-webapp/", TomcatService.forTomcat(tomcatWithoutWebApp))
     .serviceUnder("/some-webapp/", TomcatService.forTomcat(tomcatWithWebApp));
  }
};

代码示例来源:origin: spring-projects/spring-framework

@Override
protected void initServer() throws Exception {
  this.tomcatServer = new Tomcat();
  this.tomcatServer.setBaseDir(baseDir);
  this.tomcatServer.setHostname(getHost());
  this.tomcatServer.setPort(getPort());
  ServletHttpHandlerAdapter servlet = initServletAdapter();
  File base = new File(System.getProperty("java.io.tmpdir"));
  Context rootContext = tomcatServer.addContext(this.contextPath, base.getAbsolutePath());
  Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet).setAsyncSupported(true);
  rootContext.addServletMappingDecoded(this.servletMapping, "httpHandlerServlet");
  if (wsListener != null) {
    rootContext.addApplicationListener(wsListener.getName());
  }
}

代码示例来源:origin: pippo-java/pippo

tomcat.setBaseDir(getSettings().getBaseFolder());
Context context = tomcat.addContext(getSettings().getContextPath(), docBase.getAbsolutePath());
context.setAllowCasualMultipartParsing(true);
PippoServlet pippoServlet = new PippoServlet();
pippoServlet.setApplication(getApplication());
Wrapper wrapper = context.createWrapper();
String name = "pippoServlet";
wrapper.setLoadOnStartup(1);
wrapper.setServlet(pippoServlet);
context.addChild(wrapper);
context.addServletMapping(pippoFilterPath, name);
  tomcat.start();
} catch (LifecycleException e) {
  log.error("Unable to launch Tomcat", e);
  tomcat.getServer().await();

代码示例来源:origin: com.brienwheeler.apps/apps-tomcat

private void configureNetwork() throws Exception
    tomcat.setPort(port);
    tomcat.getConnector(); // seems to be needed as of Tomcat 9.0.X to ensure a connector exists
    tomcat.getService().removeConnector(tomcat.getConnector());
    keyStore.store(new FileOutputStream(keyStoreFile), keystorePass.toCharArray());
    Connector sslConnector = new Connector();
    sslConnector.setPort(sslPort);
    sslConnector.setSecure(true);
    sslConnector.setScheme("https");
    sslConnector.setAttribute("keystoreFile", keyStoreFile.getAbsolutePath());
    sslConnector.setAttribute("sslProtocol", "TLS");
    tomcat.getService().addConnector(sslConnector);

代码示例来源:origin: fabric8io/shootout-docker-maven

public static void main(String[] args) throws LifecycleException, SQLException {
  Tomcat tomcat = new Tomcat();
  tomcat.setPort(8080);
  File base = new File(System.getProperty("java.io.tmpdir"));
  Context rootCtx = tomcat.addContext("/", base.getAbsolutePath());
  Tomcat.addServlet(rootCtx, "log", new LogService());
  rootCtx.addServletMapping("/*", "log");
  tomcat.start();
  tomcat.getServer().await();
}

代码示例来源:origin: camunda/camunda-bpm-platform

int port = Integer.parseInt(serverProperties.getProperty(PORT_PROPERTY));
tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.setBaseDir(getWorkingDir());
tomcat.getHost().setAppBase(getWorkingDir());
tomcat.getHost().setAutoDeploy(true);
tomcat.getHost().setDeployOnStartup(true);
tomcat.addWebapp(tomcat.getHost(), contextPath, webAppPath);
 tomcat.start();
} catch (LifecycleException e) {
 throw new RuntimeException(e);

相关文章