嵌入式 Tomcat 背后的想法是在代码中完成通常的 Tomcat 通过配置完成的工作。因此通过注解配置servlet并不像在Tomcat中那么简单。
你会面临两个问题:
注释扫描
之间的主要区别Tomcat#addContext https://tomcat.apache.org/tomcat-10.0-doc/api/org/apache/catalina/startup/Tomcat.html#addContext-java.lang.String-java.lang.String- and Tomcat#addWebapp https://tomcat.apache.org/tomcat-10.0-doc/api/org/apache/catalina/startup/Tomcat.html#addWebapp-java.lang.String-java.lang.String-是后者添加了一些默认值web.xml
(the jsp
and default
servlet)并扫描 Servlet 3.0 注释和ServletContainerInitializer
s.
如果您不需要或不想要默认值web.xml
配置,您可以获得相同的东西:
Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());
ctx.addLifecycleListener(new ContextConfig());
资源
即使启用注释扫描后,Tomcat 也不会找到您的 servlet,因为它会查找/WEB-INF/classes
你的docBase
(您将其设置为当前文件夹)。这可能是一个空文件夹。如果您希望 Tomcat 也扫描应用程序中的类,您需要:
- 找到包含您的 JAR 文件或目录
Main
class,
- 将该 JAR 的内容安装到
/WEB-INF/classes
您的应用程序的(虚拟)文件夹(参见汤姆猫资源 http://tomcat.apache.org/tomcat-9.0-doc/config/resources.html):
public static void main(String[] args) throws LifecycleException, InterruptedException {
...
// Add the JAR/folder containing this class to PreResources
final WebResourceRoot root = new StandardRoot(ctx);
final URL url = findClassLocation(Main.class);
root.createWebResourceSet(ResourceSetType.PRE, "/WEB-INF/classes", url, "/");
ctx.setResources(root);
...
}
/*
* Tries to find the URL of the JAR or directory containing {@code clazz}.
*/
private static URL findClassLocation(Class< ? > clazz) {
return clazz.getProtectionDomain().getCodeSource().getLocation();
}
Summary
最后你会得到:
public static void main(String[] args) throws LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8082);
final Context ctx = tomcat.addContext("", Paths.get(".").toAbsolutePath().toString());
// Add the standard ContextConfig, which scans for annotations
ctx.addLifecycleListener(new ContextConfig());
// Add the JAR/folder containing this class to PreResources
final WebResourceRoot root = new StandardRoot(ctx);
final URL url = findClassLocation(Main.class);
root.createWebResourceSet(ResourceSetType.PRE, "/WEB-INF/classes", url, "/");
ctx.setResources(root);
// Run Tomcat
tomcat.getConnector();
tomcat.start();
tomcat.getServer().await();
}