How can I configure embedded tomcat to listen to port 80 and 8443?

1.2k views Asked by At

I am using embedded Tomcat with Spring and I configured it programmatically to listen to port 8443 for https and it works. Below is my code snippet from my Apllication.java file. How can I configure it to also listen to port 80 for http requests?

@Bean
    EmbeddedServletContainerCustomizer containerCustomizer(
            @Value("${keystore.file:src/main/resources/private/keystore}") String keystoreFile,
            @Value("${keystore.pass:changeit}") final String keystorePass) throws Exception {


        final String absoluteKeystoreFile = new File(keystoreFile).getAbsolutePath();

        return new EmbeddedServletContainerCustomizer () {

            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                    TomcatEmbeddedServletContainerFactory tomcat = (TomcatEmbeddedServletContainerFactory) container;



                    tomcat.addConnectorCustomizers(
                            new TomcatConnectorCustomizer() {
                                @Override
                                public void customize(Connector connector) {
                                    connector.setPort(8443);
                                    connector.setSecure(true);
                                    connector.setScheme("https");

                                    Http11NioProtocol proto = (Http11NioProtocol) connector.getProtocolHandler();
                                    proto.setSSLEnabled(true);
                                    proto.setKeystoreFile(absoluteKeystoreFile);
                                    proto.setKeystorePass(keystorePass);
                                    proto.setKeystoreType("JKS");
                                    proto.setKeyAlias("tomcat");

                                }
                            });



            }
        };
    }
1

There are 1 answers

0
Rania On BEST ANSWER

I found the solution. In the customize() method I used tomcat.addAdditionalTomcatConnectors(httpConnector()) method to add a new http port

  // create an http port for downloading images over http
    private Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setScheme("http");
            connector.setPort(8383);
            return connector;

    }