tomcat或springboot制作https证书访问

在windows cmd窗口或者shell窗口执行以下命令,根据提示输入密码和一些信息(信息随意)即可

keytool -genkey -alias tomcat -keyalg RSA -keystore ./server.keystore

执行完毕后,windows的当前用户目录可以看到server.keystore文件,linux则在当前执行目录下
一、springboot项目增加以下配置类


import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TomcatConfig {
	
	/**
	 * 将http(80/8080)流量转到https(8443)
	 */
	@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(http80Connector(),http8080Connector());
		return tomcat;
	}
	private Connector http80Connector() {
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		Http11NioProtocol protocol = (Http11NioProtocol)connector.getProtocolHandler();
		
		protocol.setMaxThreads(6000);
		protocol.setMaxConnections(20000);
		protocol.setMaxHttpHeaderSize(30000);
		connector.setScheme("http");
		connector.setPort(80);
		connector.setSecure(false);
		connector.setRedirectPort(8443);
		return connector;
	}
	private Connector http8080Connector() {
		Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
		connector.setScheme("http");
		connector.setPort(8080);
		connector.setSecure(false);
		connector.setRedirectPort(8443);
		return connector;
	}
}

修改配置文件application.properties

server.port=443
server.ssl.key-store=server.keystore
server.ssl.key-alias=tomcat
server.ssl.enabled=true
server.ssl.key-store-password=密码
server.ssl.key-store-type=JKS
server.session.cookie.max-age=3600
server.session.timeout=3600
server.tomcat.uri-encoding=UTF-8

二、如果是tomcat项目则修改servre.xml文件



  
  
  
  
  
  
    
  

  
   
    
    
      
        
      

      
        
      
    
  

你可能感兴趣的:(java)