I was having difficulty embedding tomcat, so I decided to try the simplest possible demo and work toward what I needed. It still didn't work. In fact, it doesn't even listen on port 8080. I thought there might be some garbage polluting the class path, so I put it in its own project with only one jar in the pom.xml, org.apache.tomcat.embed:tomcat-embed-core:9.0.35.
Well, I figured out that if I use version 8 of tomcat it works. Not sure why, yet.
Here is the code:
/*
* uses tomcat version 9.0.35
*/
package org.redangus.redspro.main;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
public class TomcatEmbedded {
public static void main(String[] args)
throws LifecycleException, InterruptedException, ServletException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());
final String HELLO = "hello";
Tomcat.addServlet(ctx, HELLO, new HttpServlet() {
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
try (Writer writer = response.getWriter()) {
writer.write("Hello, World!");
writer.flush();
}
}
});
ctx.addServletMappingDecoded("/*", HELLO);
tomcat.start();
tomcat.getServer().await();
}
}