SpringBoot实现http转向Https

配置SSL参考
SpringBoot配置SSL

编写测试类

package com.boot;

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.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//控制器@RestController可以省略方法上@ResponseBody 
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})//springboot启动支持注解,exclude= {DataSourceAutoConfiguration.class}用于关闭特定的自动配置
public class SpringbootApplication {
	
	//自动获取properties中配置的user.author赋值于author
	@Value("${user.author}")
	private String author;
	//自动获取properties中配置的user.name赋值于name
	@Value("${user.proname}")
	private String proname;
	
	
	@RequestMapping("/")
	public String index() {
		return "测试获取的author="+author+"===proname="+proname;
	}
	
	@Bean
	public TomcatServletWebServerFactory servletContainer() {
		TomcatServletWebServerFactory tomcat=new TomcatServletWebServerFactory() {
			 @Override
	            protected void postProcessContext(Context context) {
	                SecurityConstraint constraint = new SecurityConstraint();
	                constraint.setUserConstraint("CONFIDENTIAL");
	                SecurityCollection collection = new SecurityCollection();
	                collection.addPattern("/*");
	                constraint.addCollection(collection);
	                context.addConstraint(constraint);
			 }
		};
		tomcat.addAdditionalTomcatConnectors(httpConnector());
		return tomcat;
	}
	
	@Bean
	public Connector httpConnector() {
		Connector con=new Connector("org.apache.coyote.http11.Http11NioProtocol");
		//监听http的端口号
		con.setScheme("http");
		con.setPort(80);
		
		con.setSecure(false);
		//转向https端口号
		con.setRedirectPort(443);
		return con;
	}

	public static void main(String[] args) {
		SpringApplication.run(SpringbootApplication.class, args);//springboot启动入口
	}
}

启动服务,浏览器输入http://localhost/boot测试
在这里插入图片描述
在这里插入图片描述
测试成功已自动转向

你可能感兴趣的:(SpringBoot)