下面列出了org.springframework.boot.web.servlet.server.ServletWebServerFactory#org.apache.catalina.startup.Tomcat 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Setup the test by deploying an embedded tomcat and adding the rest endpoints.
* @throws Throwable Throws uncaught throwables for test to fail.
*/
@Before
public void setup() throws Throwable {
registryTomcat = new Tomcat();
registryTomcat.setPort(3000);
registryTomcat.setBaseDir(testWorkingDir);
Context context = registryTomcat.addWebapp(CONTEXT, testWorkingDir);
context.addApplicationListener(RegistryStartup.class.getName());
ResourceConfig restServletConfig = new ResourceConfig();
restServletConfig.register(RegistryREST.class);
restServletConfig.register(Registry.class);
ServletContainer restServlet = new ServletContainer(restServletConfig);
registryTomcat.addServlet(CONTEXT, "restServlet", restServlet);
context.addServletMappingDecoded("/rest/*", "restServlet");
registryTomcat.start();
}
@Test
public void bug54241b() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() +
"/test/bug5nnnn/bug54241b.jsp", res, null);
Assert.assertEquals(res.toString(),
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
}
@Test
public void testDirContextAliases() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Must have a real docBase - just use temp
StandardContext ctx = (StandardContext)
tomcat.addContext("", System.getProperty("java.io.tmpdir"));
File lib = new File("webapps/examples/WEB-INF/lib");
ctx.setAliases("/WEB-INF/lib=" + lib.getCanonicalPath());
Tomcat.addServlet(ctx, "test", new TestServlet());
ctx.addServletMapping("/", "test");
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
String result = res.toString();
assertTrue(result.indexOf("00-PASS") > -1);
assertTrue(result.indexOf("01-PASS") > -1);
assertTrue(result.indexOf("02-PASS") > -1);
}
@Test
public void testServlet23NoEL() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir =
new File("test/webapp-2.3");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/el-as-literal.jsp");
String result = res.toString();
assertTrue(result.indexOf("<p>00-${'hello world'}</p>") > 0);
assertTrue(result.indexOf("<p>01-#{'hello world'}</p>") > 0);
}
@Test
public void testSecurityAnnotationsNoWebXmlLoginConfig() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0-servletsecurity2");
tomcat.addWebapp(null, "", appDir.getAbsolutePath());
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() + "/protected.jsp",
bc, null, null);
assertTrue(bc.getLength() > 0);
assertEquals(403, rc);
bc.recycle();
rc = getUrl("http://localhost:" + getPort() + "/unprotected.jsp",
bc, null, null);
assertEquals(200, rc);
assertTrue(bc.toString().contains("00-OK"));
}
private void doTestNonBlockingRead(boolean ignoreIsReady, boolean async) throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
NBReadServlet servlet = new NBReadServlet(ignoreIsReady, async);
String servletName = NBReadServlet.class.getName();
Tomcat.addServlet(ctx, servletName, servlet);
ctx.addServletMappingDecoded("/", servletName);
tomcat.start();
Map<String, List<String>> resHeaders = new HashMap<>();
int rc = postUrl(true, new DataWriter(async ? 0 : 500, async ? 2000000 : 5),
"http://localhost:" + getPort() + "/", new ByteChunk(), resHeaders, null);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
if (async) {
Assert.assertEquals(2000000 * 8, servlet.listener.body.length());
} else {
Assert.assertEquals(5 * 8, servlet.listener.body.length());
}
}
@Test
public void testGetJspConfigDescriptor() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0");
// app dir is relative to server home
StandardContext standardContext = (StandardContext) tomcat.addWebapp(
null, "/test", appDir.getAbsolutePath());
ServletContext servletContext = standardContext.getServletContext();
Assert.assertNull(servletContext.getJspConfigDescriptor());
tomcat.start();
Assert.assertNotNull(servletContext.getJspConfigDescriptor());
}
@Test
public void testServlet24NoEL() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-2.4");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/el-as-literal.jsp");
String result = res.toString();
Assert.assertTrue(result.indexOf("<p>00-hello world</p>") > 0);
Assert.assertTrue(result.indexOf("<p>01-#{'hello world'}</p>") > 0);
}
private void doTestInvalidate(boolean useClustering) throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "bug56578", new Bug56578Servlet());
ctx.addServletMappingDecoded("/bug56578", "bug56578");
if (useClustering) {
tomcat.getEngine().setCluster(new SimpleTcpCluster());
ctx.setDistributable(true);
ctx.setManager(ctx.getCluster().createManager(""));
}
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() + "/bug56578");
Assert.assertEquals("PASS", res.toString());
}
@Override
protected void init(Context ctx) {
final FilterDef filterDef = new FilterDef();
filterDef.setFilter(testFilter);
filterDef.setFilterName("filter");
ctx.addFilterDef(filterDef);
final FilterMap filterMap = new FilterMap();
filterMap.addURLPattern("/*");
filterMap.setFilterName("filter");
ctx.addFilterMap(filterMap);
Tomcat.addServlet(ctx, "test", testServlet);
Tomcat.addServlet(ctx, "gzip", gzipTestServlet);
ctx.addServletMapping("/test/*", "test");
ctx.addServletMapping("/gzip/*", "gzip");
}
@Test
public void testBug36923() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug36923.jsp");
String result = res.toString();
assertEcho(result, "00-${hello world}");
}
private void doTestBug53677(boolean flush) throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctxt = tomcat.addContext("", null);
Tomcat.addServlet(ctxt, "LargeHeaderServlet",
new LargeHeaderServlet(flush));
ctxt.addServletMapping("/test", "LargeHeaderServlet");
tomcat.start();
ByteChunk responseBody = new ByteChunk();
Map<String,List<String>> responseHeaders =
new HashMap<String,List<String>>();
int rc = getUrl("http://localhost:" + getPort() + "/test", responseBody,
responseHeaders);
assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc);
if (responseBody.getLength() > 0) {
// It will be >0 if the standard error page handlign has been
// triggered
assertFalse(responseBody.toString().contains("FAIL"));
}
}
@Test
public void testSecurityAnnotationsWebXmlPriority() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0-fragments");
tomcat.addWebapp(null, "", appDir.getAbsolutePath());
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() +
"/testStandardWrapper/securityAnnotationsWebXmlPriority",
bc, null, null);
assertTrue(bc.getLength() > 0);
assertEquals(403, rc);
}
@Test
public void bug54241a() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0");
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() +
"/test/bug5nnnn/bug54241a.jsp", res, null);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
String body = res.toString();
Assert.assertTrue(body.contains("01: null"));
Assert.assertTrue(body.contains("02: null"));
}
@Test
public void testClientDropsConnection() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
ctx.addApplicationListener(Bug58624Config.class.getName());
Tomcat.addServlet(ctx, "default", new DefaultServlet());
ctx.addServletMapping("/", "default");
WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
tomcat.start();
SimpleClient client = new SimpleClient();
URI uri = new URI("ws://localhost:" + getPort() + Bug58624Config.PATH);
Session session = wsContainer.connectToServer(client, uri);
// Break point A required on following line
session.close();
}
private synchronized void init(int status, boolean swallow)
throws Exception {
if (init)
return;
Tomcat tomcat = getTomcatInstance();
context = tomcat.addContext("", TEMP_DIR);
AbortedPOSTServlet servlet = new AbortedPOSTServlet();
servlet.setStatus(status);
Tomcat.addServlet(context, servletName,
servlet);
context.addServletMapping(URI, servletName);
context.setSwallowAbortedUploads(swallow);
tomcat.start();
setPort(tomcat.getConnector().getLocalPort());
init = true;
}
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());
log.info("-----------------------------------------------------------------");
log.info("Starting Tomcat port {} dir {}", port, webappsPath);
log.info("-----------------------------------------------------------------");
tomcat.start();
while ( true ) {
Thread.sleep(1000);
}
}
@Test
public void testSecurityAnnotationsNoWebXmlConstraints() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0-servletsecurity");
tomcat.addWebapp(null, "", appDir.getAbsolutePath());
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() + "/",
bc, null, null);
assertTrue(bc.getLength() > 0);
assertEquals(403, rc);
}
/**
* Check https://jira.springsource.org/browse/SPR-7350 isn't really an issue
*/
@Test
public void testLookupException() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0-fragments");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk bc = getUrl("http://localhost:" + getPort() +
"/test/warDirContext.jsp");
assertEquals("<p>java.lang.ClassNotFoundException</p>",
bc.toString());
}
private void doTestNon2xxResponseAndExpectation(boolean useExpectation) throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Tomcat.addServlet(ctx, "echo", new EchoBodyServlet());
ctx.addServletMapping("/echo", "echo");
SecurityCollection collection = new SecurityCollection("All", "");
collection.addPattern("/*");
SecurityConstraint constraint = new SecurityConstraint();
constraint.addAuthRole("Any");
constraint.addCollection(collection);
ctx.addConstraint(constraint);
tomcat.start();
Non2xxResponseClient client = new Non2xxResponseClient(useExpectation);
client.setPort(getPort());
client.doResourceRequest("GET http://localhost:" + getPort()
+ "/echo HTTP/1.1", "HelloWorld");
Assert.assertTrue(client.isResponse403());
Assert.assertTrue(client.checkConnectionHeader());
}
private synchronized void init() throws Exception {
if (init) return;
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context root = tomcat.addContext("", null);
Tomcat.addServlet(root, "EchoParameters", new EchoParametersServlet());
root.addServletMapping("/echo", "EchoParameters");
tomcat.start();
setPort(tomcat.getConnector().getLocalPort());
init = true;
}
/**
* Run the test.
* @throws ServletException Exception on fail.
* @throws LifecycleException Exception on fail.
* @throws InterruptedException Exception on fail.
*/
@Test
public void test() throws ServletException, LifecycleException, InterruptedException {
Tomcat store1 = new Tomcat();
createClientTomcat(Service.AUTH, store1);
waitAndValidate(Service.AUTH, new String[] {"40008"});
Tomcat store2 = new Tomcat();
createClientTomcat(Service.AUTH, store2);
waitAndValidate(Service.AUTH, new String[] {"40008", "40009"});
store2.stop();
waitAndValidate(Service.AUTH, new String[] {"40008"});
}
@Test
public void testBug42565() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0");
// app dir is relative to server home
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk res = getUrl("http://localhost:" + getPort() +
"/test/bug42565.jsp");
String result = res.toString();
assertEcho(result, "00-false");
assertEcho(result, "01-false");
assertEcho(result, "02-false");
assertEcho(result, "03-false");
assertEcho(result, "04-false");
assertEcho(result, "05-false");
assertEcho(result, "06-false");
assertEcho(result, "07-false");
assertEcho(result, "08-false");
assertEcho(result, "09-false");
assertEcho(result, "10-false");
assertEcho(result, "11-false");
assertEcho(result, "12-false");
assertEcho(result, "13-false");
assertEcho(result, "14-false");
assertEcho(result, "15-false");
}
@Test
public void testHeaderLimits1() throws Exception {
// Bumping into maxHttpHeaderSize
Tomcat tomcat = getTomcatInstance();
setupHeadersTest(tomcat);
tomcat.getConnector().setMaxHeaderCount(-1);
runHeadersTest(false, tomcat, 8 * 1024, -1);
}
@Override
public void setUp() throws Exception {
super.setUp();
// Configure a context with digest auth and a single protected resource
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctxt = tomcat.addContext(CONTEXT_PATH, null);
// Add protected servlet
Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
ctxt.addServletMappingDecoded(URI, "TesterServlet");
SecurityCollection collection = new SecurityCollection();
collection.addPatternDecoded(URI);
SecurityConstraint sc = new SecurityConstraint();
sc.addAuthRole(ROLE);
sc.addCollection(collection);
ctxt.addConstraint(sc);
// Configure the Realm
TesterMapRealm realm = new TesterMapRealm();
realm.addUser(USER, PWD);
realm.addUserRole(USER, ROLE);
ctxt.setRealm(realm);
// Configure the authenticator
LoginConfig lc = new LoginConfig();
lc.setAuthMethod("DIGEST");
lc.setRealmName(REALM);
ctxt.setLoginConfig(lc);
ctxt.getPipeline().addValve(new DigestAuthenticator());
}
private Exception doRequest() {
Tomcat tomcat = getTomcatInstance();
Context root = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(root, "Bug54947", new TesterServlet());
root.addServletMapping("/test", "Bug54947");
try {
tomcat.start();
setPort(tomcat.getConnector().getLocalPort());
// Open connection
connect();
String[] request = new String[2];
request[0] = "GET http://localhost:8080/test HTTP/1.1" + CR;
request[1] = LF +
"Connection: close" + CRLF +
CRLF;
setRequest(request);
processRequest(); // blocks until response has been read
// Close the connection
disconnect();
} catch (Exception e) {
return e;
}
return null;
}
private FormAuthClient(boolean clientShouldUseCookies,
boolean serverShouldUseCookies,
boolean serverShouldChangeSessid) throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File(getBuildDirectory(), "webapps/examples");
Context ctx = tomcat.addWebapp(null, "/examples",
appDir.getAbsolutePath());
setUseCookies(clientShouldUseCookies);
ctx.setCookies(serverShouldUseCookies);
MapRealm realm = new MapRealm();
realm.addUser("tomcat", "tomcat");
realm.addUserRole("tomcat", "tomcat");
ctx.setRealm(realm);
tomcat.start();
// perhaps this does not work until tomcat has started?
ctx.setSessionTimeout(TIMEOUT_MINS);
// Valve pipeline is only established after tomcat starts
Valve[] valves = ctx.getPipeline().getValves();
for (Valve valve : valves) {
if (valve instanceof AuthenticatorBase) {
((AuthenticatorBase)valve)
.setChangeSessionIdOnAuthentication(
serverShouldChangeSessid);
break;
}
}
// Port only known after Tomcat starts
setPort(getPort());
}
@Override
public void setUp() throws Exception {
super.setUp();
AprLifecycleListener listener = new AprLifecycleListener();
Assume.assumeTrue(AprLifecycleListener.isAprAvailable());
Assume.assumeTrue(JreCompat.isJre8Available());
Tomcat tomcat = getTomcatInstance();
Connector connector = tomcat.getConnector();
connector.setPort(0);
connector.setScheme("https");
connector.setSecure(true);
connector.setProperty("SSLEnabled", "true");
connector.setProperty("sslImplementationName", sslImplementationName);
sslHostConfig.setProtocols("TLSv1.2");
connector.addSslHostConfig(sslHostConfig);
StandardServer server = (StandardServer) tomcat.getServer();
server.addLifecycleListener(listener);
// Simple webapp
Context ctxt = tomcat.addContext("", null);
Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet());
ctxt.addServletMappingDecoded("/*", "TesterServlet");
}
@Test
public void testStartInternal() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp");
StandardContext ctx = (StandardContext) tomcat.addContext("",
appDir.getAbsolutePath());
WebappLoader loader = new WebappLoader();
loader.setContext(ctx);
ctx.setLoader(loader);
ctx.setResources(new StandardRoot(ctx));
ctx.resourcesStart();
File f1 = new File("test/webapp-fragments/WEB-INF/lib");
ctx.getResources().createWebResourceSet(
WebResourceRoot.ResourceSetType.POST, "/WEB-INF/lib",
f1.getAbsolutePath(), null, "/");
loader.start();
String[] repos = loader.getLoaderRepositories();
Assert.assertEquals(4,repos.length);
loader.stop();
repos = loader.getLoaderRepositories();
Assert.assertEquals(0, repos.length);
// no leak
loader.start();
repos = loader.getLoaderRepositories();
Assert.assertEquals(4,repos.length);
// clear loader
ctx.setLoader(null);
// see tearDown()!
tomcat.start();
}
private void doMaxMessageSize(String path, long size, boolean expectOpen)
throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
Tomcat.addServlet(ctx, "default", new DefaultServlet());
ctx.addServletMapping("/", "default");
tomcat.start();
WebSocketContainer wsContainer =
ContainerProvider.getWebSocketContainer();
Session s = connectToEchoServer(wsContainer, new EndpointA(), path);
StringBuilder msg = new StringBuilder();
for (long i = 0; i < size; i++) {
msg.append('x');
}
s.getBasicRemote().sendText(msg.toString());
// Wait for up to 5 seconds for session to close
boolean open = s.isOpen();
int count = 0;
while (open != expectOpen && count < 50) {
Thread.sleep(100);
count++;
open = s.isOpen();
}
Assert.assertEquals(Boolean.valueOf(expectOpen),
Boolean.valueOf(s.isOpen()));
}