springboot配置https,并使用wss

学习链接

springboot如何将http转https

SpringBoot配置HTTPS及开发调试

Tomcat8.5配置https和SpringBoot配置https

可借鉴的参考:

文章目录

步骤

搭建springboot基础项目

pom.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/>
    </parent>

    <groupId>org.example</groupId>
    <artifactId>demo-springboot-https</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

    <build>
        <finalName>demo-springboot-https</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- maven 打包时跳过测试 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

TomcatHttpsConfig

java 复制代码
@Configuration
public class TomcatHttpsConfig {

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @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(redirectConnector8080());
        return tomcat;
    }

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


}

WebSocketConfig

java 复制代码
@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private WsHandler wsHandler;

    @Autowired
    private WsHandshakeInterceptor wsHandshakeInterceptor;


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry
                // 设置处理器处理/custom/**
                .addHandler(wsHandler, "/wsTest/websocket")
                // 允许跨越
                .setAllowedOrigins("*")
                // 设置监听器
                .addInterceptors(wsHandshakeInterceptor);
    }

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @Bean
    public ServletServerContainerFactoryBean serverContainer() {
        ServletServerContainerFactoryBean containerFactoryBean = new ServletServerContainerFactoryBean();
        containerFactoryBean.setMaxTextMessageBufferSize(2 * 1024 * 1024);
        return containerFactoryBean;
    }
}

WsHandler

java 复制代码
@Slf4j
@Component
public class WsHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        log.info("收到客户端数据: {}", message.getPayload());
        session.sendMessage(new TextMessage("收到了您的消息"));
    }
}

WsHandshakeInterceptor

java 复制代码
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("beforeHandsShake...握手前");
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        log.info("beforeHandsShake...握手后");
    }

}

application.yml

yml 复制代码
server:
  port: 8081
  ssl:
    key-store: tomcat.keystore
    key-alias: tomcat
    enabled: true
    key-store-type: JKS
    key-store-password: 123456

TestApplication

java 复制代码
@SpringBootApplication
public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

index.html

html 复制代码
<html>
<head>
    <meta charset="utf8"/>
</head>
    <body>
        <h1>hello word!!!</h1>
        <p>this is a html page</p>
        <input type="text" id="ipt" value="wss://192.168.134.5:8081/wsTest/websocket" style="width: 1200px">
        <br/>
        <button type="button" id="btn">连接ws</button>
    </body>
    <script>
        var ws = null
        const btn = document.querySelector('#btn')
        btn.onclick = function(){
            console.log('halo')
            const ipt = document.querySelector('#ipt')
            console.log(ipt.value)
            ws = new WebSocket(ipt.value)
            ws.onopen = () => {
                console.log('连接成功')
            }
            ws.onmessage = (msg) => {
                console.log('收到消息: ' + msg)
            }
            ws.onerror = (err) => {
                console.log('连接失败: ' + err)
            }
        }
    </script>
</html>

生成安全证书

sh 复制代码
keytool -genkey -alias tomcat -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore D:/tmp/tomcat.keystore -storepass 123456

将证书放到项目目录下

访问

访问http://192.168.134.5:8080时,会自动跳转到https://192.168.134.5:8081,由于是自签名证书,所以会有安全警告,点击继续

看到下方页面

点击上面的连接ws,可以看到连接成功了

相关推荐
计算机毕设vx_bysj68692 小时前
计算机毕业设计必看必学~Springboot教学进度管理系统,原创定制程序、单片机、java、PHP、Python、小程序、文案全套、毕设成品等!
java·spring boot·vue·课程设计·管理系统
谢尔登2 小时前
HTTPS 究竟比 HTTP 好在哪?
http·https·ssl
q***11653 小时前
Spring 中的 @ExceptionHandler 注解详解与应用
java·后端·spring
用户21411832636024 小时前
Gemini 3 Pro 来了!一句话生成完整网站,AI编程能力断层领先
后端
码事漫谈5 小时前
Linux开发到底指什么?是什么岗位?做什么的?
后端
码事漫谈5 小时前
Windows开发:一场与指针的共舞,亦是超越它的征程
后端
f***45325 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
Felix_XXXXL6 小时前
mysql查看binlog日志
java·后端
leonardee6 小时前
Plugin ‘mysql_native_password‘ is not loaded`
java·后端
百锦再6 小时前
第17章 模式与匹配
开发语言·后端·python·rust·django·内存·抽象