如何配置嵌入式tomcat来侦听端口80和8443?

时间:2014-11-17 17:13:47

标签: tomcat spring-security spring-java-config embedded-tomcat-7 embedded-tomcat-8

我正在使用嵌入式Tomcat和Spring,我以编程方式配置它来监听端口8443以获取https并且它可以工作。下面是我的Apllication.java文件中的代码片段。如何将其配置为还侦听端口80的http请求?

@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 个答案:

答案 0 :(得分:1)

我找到了解决方案。在customize()方法中我用tomcat.addAdditionalTomcatConnectors(httpConnector())方法添加一个新的http端口

  // 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;

    }