I want to set my servlet as default handler at "/" in my Tomcat embedded project but it always return a 404 error on navigator. But if I set an index.html in webapp it can return and I can access to the servlet if I set the pattern to "/app" or something like that.
(I use tomcat 11.0 but I can go to tomcat 10.0 not below)
Here my class :
public class TomcatServer implements Server { private static final Logger LOGGER = LoggerFactory.getLogger(TomcatServer.class); private static final int DEFAULT_PORT = 8080; private static final String DEFAULT_HOST = "localhost"; private static final String DOC_BASE = "."; private static final String DEFAULT_CONTEXT_PATH = "/"; @Override public void run(HttpServlet servlet) throws Exception { ConfigurationProcess config = new ConfigurationProcess(this); Tomcat tomcat = tomcat(config, servlet); try { tomcat.start(); } catch (LifecycleException e) { LOGGER.error("{}", e.getMessage()); System.exit(1); } LOGGER.info("Application started with URL {}.", tomcat.getHost().getName() +":" + tomcat.getConnector().getPort() + DEFAULT_CONTEXT_PATH); tomcat.getServer().await(); } private int getPort(ConfigurationProcess config) { String port; if ((port = config.getProperty("port")) != null) { try { return Integer.parseInt(port); } catch (NumberFormatException e) { LOGGER.error("Invalid port number argument {}", port, e); } } LOGGER.info("No port specified; defaulting to port 8080"); return DEFAULT_PORT; } private String getHostName(ConfigurationProcess config) { String hostName; if ((hostName = config.getProperty("hostname")) != null) { return hostName; } LOGGER.info("No host name specified; defaulting to 'localhost'"); return DEFAULT_HOST; } private Tomcat tomcat(ConfigurationProcess config, HttpServlet servlet) { Tomcat tomcat = new Tomcat(); tomcat.setHostname(getHostName(config)); tomcat.getHost().setAppBase(DOC_BASE); tomcat.setPort(getPort(config)); tomcat.getConnector(); context(tomcat, config, servlet); tomcat.setBaseDir(new File("temp").getAbsolutePath()); return tomcat; } private Context context(Tomcat tomcat, ConfigurationProcess config, HttpServlet servlet) { String contextPath = ""; String webapp = new File("src/main/webapp").getAbsolutePath(); Context context = tomcat.addWebapp(contextPath, webapp); context.setDocBase(webapp); context.setReloadable(true); tomcat.addServlet(contextPath, servlet.getClass().getName(), servlet); context.addServletMappingDecoded("/", servlet.getClass().getName()); return context; }}
I already tried to change the context path but still doesn't work, I tried to remove the mapping to "/" before to set it to my servlet still doesn't work. I expect when I call localhost:8080/ it return my servlet.