spirngboot项目中在启动类中添加完SSL证书(http改为hppts),以下为添加的证书:
/**
* 以下为配置SSL
* @return
*/
@Bean
public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection securityCollection = new SecurityCollection();
securityCollection.addPattern("/*");
securityConstraint.addCollection(securityCollection);
context.addConstraint(securityConstraint);
}
};
factory.addAdditionalTomcatConnectors(httpConnector());
return factory;
}
@Bean
public Connector httpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
// http的端口
connector.setPort(http端口号);
connector.setSecure(false);
// http的端口后转向到的https的端口
connector.setRedirectPort(https端口号);
return connector;
}
添加SSL证书的applicaton配置,自己搜一下就可以找到,然后根据自己的改就行了。
而配置完后postman可以正常访问,但是浏览器中出现标题的报错,或者跨域cors问题。
跨域解决:
1、后端启动类中加:
/**
* 跨域问题
* @return
*/
@Bean
public WebMvcConfigurer corsConfigurer () {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","POST","PUT","HEAD")
.allowCredentials(true)
.allowedHeaders("*")
.maxAge(3600);
}
};
}
private static final long MAX_AGE = 24*60*60;
@Bean
public CorsFilter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(source);
}
加完之后几乎可以解决问题了,但有的浏览器还是存在标题中的报错,这个就需要前端将访问的接口替换掉,例如:
你的访问路径为 https://x2.x2.x2.x2:8080/ (端口号根据你自己的项目来定) , 替换成你的ssl证书所绑定的域名:https://www.baidu.com:443(端口号根据你自己的项目来定)
做到这一步基本就已经告别标题上的报错了。