diff --git a/src/main/java/com/campus/water/config/HttpsConfig.java b/src/main/java/com/campus/water/config/HttpsConfig.java new file mode 100644 index 0000000..c96c636 --- /dev/null +++ b/src/main/java/com/campus/water/config/HttpsConfig.java @@ -0,0 +1,46 @@ +package com.campus.water.config; +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; + +import java.io.IOException; + +@Configuration +public class HttpsConfig { + + // 优先级最高的过滤器,实现HTTP→HTTPS跳转 + @Bean + @Order(Ordered.HIGHEST_PRECEDENCE) + public Filter httpToHttpsRedirectFilter() { + return new Filter() { + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse res = (HttpServletResponse) response; + + // 仅处理HTTP请求,跳转到HTTPS + if ("http".equals(req.getScheme())) { + String httpsUrl = "https://" + req.getServerName() + ":" + 8081 + req.getRequestURI(); + if (req.getQueryString() != null) { + httpsUrl += "?" + req.getQueryString(); + } + res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); + res.setHeader("Location", httpsUrl); + return; + } + chain.doFilter(request, response); + } + + @Override + public void init(FilterConfig filterConfig) {} + + @Override + public void destroy() {} + }; + } +} \ No newline at end of file diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 948eb44..fb97b49 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -35,4 +35,12 @@ server: charset: UTF-8 enabled: true force: true - port: 8080 \ No newline at end of file + port: 8081 + ssl: + key-store: classpath:keystore.p12 + key-store-password: 123456 + key-store-type: PKCS12 + key-alias: myhttps + additional-ports: + - port: 8080 + protocol: HTTP \ No newline at end of file