Spring Boot redirect port 8080 to 8443

In Spring Boot 2.x, we can create a ServletWebServerFactory to redirect a port from HTTP 8080 to HTTPS 8443.

Access localhost:8080, it will redirect to localhost:8443

1. ServletWebServerFactory

For Spring Boot 2.x, try this:

pom.xml

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
StartApplication.java

package com.mkyong;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class StartApplication {
    public static void main(String[] args) {
        SpringApplication.run(StartApplication.class, args);
    }

    // spring boot 2.x
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

    private Connector redirectConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }

}

2. EmbeddedServletContainerFactory

For Spring Boot 1.x, try EmbeddedServletContainerFactory


  @Bean
  public EmbeddedServletContainerFactory servletContainer() {
      TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
          @Override
          protected void postProcessContext(Context context) {
              SecurityConstraint securityConstraint = new SecurityConstraint();
              securityConstraint.setUserConstraint("CONFIDENTIAL");
              SecurityCollection collection = new SecurityCollection();
              collection.addPattern("/*");
              securityConstraint.addCollection(collection);
              context.addConstraint(securityConstraint);
          }
      };

      tomcat.addAdditionalTomcatConnectors(redirectConnector());
      return tomcat;
  }

  private Connector redirectConnector() {
      Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      connector.setScheme("http");
      connector.setPort(8080);
      connector.setSecure(false);
      connector.setRedirectPort(8443);

      return connector;
  }

References

5 comments on “Spring Boot redirect port 8080 to 8443

  1. ERROR org.springframework.boot.SpringApplication – Application run failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘resourceHandlerMapping’ defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/W
    ebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantia
    te [org.springframework.web.servlet.HandlerMapping]: Factory method ‘resourceHandlerMapping’ threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:635)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556)
       

    Reply
  2. Getting error while launching

    2020-02-23 21:46:15.743 INFO 19380 — [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit ‘default’
    2020-02-23 21:46:15.843 WARN 19380 — [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
    2020-02-23 21:46:16.114 INFO 19380 — [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService ‘applicationTaskExecutor’
    2020-02-23 21:46:16.464 INFO 19380 — [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
    2020-02-23 21:46:16.479 INFO 19380 — [ main] ConditionEvaluationReportLoggingListener :

    Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug’ enabled.
    2020-02-23 21:46:16.482 ERROR 19380 — [ main] o.s.b.d.LoggingFailureAnalysisReporter :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Web server failed to start. Port 8080 was already in use.

    Action:

    Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port.

    2020-02-23 21:46:16.486 INFO 19380 — [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService ‘applicationTaskExecutor’
    2020-02-23 21:46:16.486 INFO 19380 — [ main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit ‘default’
    2020-02-23 21:46:16.487 INFO 19380 — [ main] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down’
    2020-02-23 21:46:16.493 INFO 19380 — [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 – Shutdown initiated…
    2020-02-23 21:46:16.503 INFO 19380 — [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 – Shutdown completed.

    Reply
      1. It’s not a desicion. I have the same problem. It’s not an other program, it is this program. By default Tomcat has started by 8080 (server.port) and you try to set port for Connector to 8080.
        Do you know how to solve this problem?

        Reply

Leave a Comment

Your email address will not be published. Required fields are marked *