1

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();
    }
}
user3416742
  • 168
  • 1
  • 1
  • 7
  • 1
    Does this answer your question? [Code works with Embedded Apache Tomcat 8 but not with 9. What's changed?](https://stackoverflow.com/questions/48998387/code-works-with-embedded-apache-tomcat-8-but-not-with-9-whats-changed) – andrewJames Jun 13 '20 at 17:52

0 Answers0