給你的項目配置個https吧

1.申請證書

這裡我選擇的是阿里雲的個人免費的證書

給你的項目配置個https吧

因為使用的是內置的Tomcat,所以下載Tomcat類型的

給你的項目配置個https吧

2.配置項目

將證書XXXX.pfx文件放到項目的resources目錄,接著修改application.yml文件

<code>

server

:

port

:

443

ssl

:

key-store

:

classpath

:XXXX.pfx

key-store-password

: 證書密碼

keyStoreType

: PKCS12/<code>

接著修改啟動類,添加如下內容,接著啟動項目

<code>

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.context.embedded.ConfigurableEmbeddedServletContainer;

import

org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;

import

org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;

import

org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;

import

org.springframework.context.annotation.Bean;

import

org.mybatis.spring.annotation.MapperScan;

import

org.springframework.scheduling.annotation.EnableAsync;

import

org.springframework.scheduling.annotation.EnableScheduling;

import

org.springframework.transaction.annotation.EnableTransactionManagement;

public

class

MxemApplication

implements

EmbeddedServletContainerCustomizer

{

public

EmbeddedServletContainerFactory

servletContainer

()

{ TomcatEmbeddedServletContainerFactory tomcat =

new

TomcatEmbeddedServletContainerFactory() {

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; }

public

Connector

httpConnector

()

{ Connector connector =

new

Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL); connector.setScheme(

"http"

); connector.setPort(

80

); connector.setSecure(

false

); connector.setRedirectPort(

443

);

return

connector; }

public

void

customize

(ConfigurableEmbeddedServletContainer container)

{ container.setPort(

443

); } }/<code>

3.可能出現的問題

可能會出現下面的錯誤

<code>Address already in 

use

:

bind

/<code>

解決辦法

以windows系統為例,查看當前端口被哪個進程佔用了(進入到CMD中)

<code>

netstat

-ano|findstr

"443"

/<code>

然後找到進程ID,使用任務管理器結束此進程即可。

如果對你有幫助,還請點個贊,點個關注

給你的項目配置個https吧


分享到:


相關文章: