简体   繁体   中英

How to redirect from http to https in Spring Boot?

my website is using https protocol. When I do a action like submit a form, it redirect to http, not to https. I used this way.

@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(createHttpConnector());
   return tomcat;
}


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

But It show error when building "Address already in use: bind". Could you hep me resolve this problem?

you have to kill process for that particular port

In windows

netstat -ano

will list all the protocols, ports and processes listening . Use

taskkill -pid "proces to kill" /f

to kill the process listening to the port. eg

 taskkill -pid 431 /f

In Linux

If you know what port the process is running you can type: lsof -i:<port> .

For instance, lsof -i:8080 , to list the process (pid) running on port 8080.

Then kill the process with kill <pid> .

If after running above step it does not work than verify your step

For Enabling HTTPS in Spring Boot follow these three step.

Step 1.Get yourself a SSL certificate: generate a self-signed certifcate or get one from a Certificate Authority

Step 2.Enable HTTPS in Spring Boot.

  • add below configuration in application.properties file at location src/main/resources

     server.port: 8443 server.ssl.key-store: <keystore> (egkeystore.p12) server.ssl.key-store-password: <key-store-password> (egmypassword) server.ssl.keyStoreType: <keyStoreType>(egPKCS12) server.ssl.keyAlias: tomcat 

Step 3.Redirect HTTP to HTTPS (Which you already completed)

For more details refer Enable HTTPS in Spring Boot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM