Spring Boot 配置http与https


placeholder image
admin 发布于:2022-05-09 21:54:20
阅读:loading

本站博客1.0的实现有使用到了基于https安全协议访问,大概的实现是从阿里云申请免费的https证数(有效期一年,过期可继续申请),加上外置的Tomcat进行的参数配置,实现的https访问支持(当访问的是http协议时自动跳转至https)。那么本站2.0基于Spring Boot技术架构实现的,自然需要考虑这一特性,所以本篇文章主要实现的是让example项目同时支持http和https两种协议的支持,详细实现如下。

https证数下载

关于https证数的下载可从阿里云免费下载,同时也可以使用JDK bin目录中的命令行工具keytool自行生成证数。本次选择稍微熟悉点的阿里云证数,所以跳过具体证数的下载(本站的全局搜索功能能够搜到到关于https文章试提到的免费证数下载及配置相关的文章)。

配置http和https

application.yaml

#server
server:
  port: 443
  http-port: 80
  servlet:
    context-path: /
  ssl:
    enabled: true
    key-store: "classpath:ssl/www.chendd.cn.pfx"
    key-store-password: z1JSquRD

Boostrap.java

package cn.chendd;

import ...;

/**
 * 启动类
 *
 * @author chendd
 * @date 2022/5/8 20:09
 */
@SpringBootApplication(exclude = {FreeMarkerAutoConfiguration.class})
@Import(value = {ContextConfiguration.class , SwaggerConfiguration.class , FreemarkerConfiguration.class})
public class Bootstrap {

    /**
     * 服务器启动
     * @param args 启动参数
     */
    public static void main(String[] args) {
        SoutCounter.sign("Bootstrap.main###启动类启动前输出一句话");
        SpringApplication.run(Bootstrap.class , args);
        SoutCounter.sign("Bootstrap.main###启动类启动后输出一句话");
    }

    @Value("${server.http-port}")
    private Integer httpPort;

    @Value("${server.port}")
    private Integer httpsPort;

    /**
     * 定制web-server服务器,绑定http访问协议与端口等
     * @return server服务器设置
     */
    @Bean
    public TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                //设置安全性约束
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint(ServletSecurity.TransportGuarantee.CONFIDENTIAL.name());
                //设置约束条件
                SecurityCollection collection = new SecurityCollection();
                //拦截所有请求
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        //设置http访问
        Connector httpConnector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        httpConnector.setPort(httpPort);
        httpConnector.setRedirectPort(httpsPort);
        ///如果设置了setSecure为true则http不会自动转向至https
        //httpConnector.setSecure(true);
        tomcat.addAdditionalTomcatConnectors(httpConnector);
        return tomcat;
    }

    @RestController
    public static class IndexController {

        @RequestMapping(value = "/")
        public void index(HttpServletRequest request , HttpServletResponse response) throws IOException {
            StringBuffer requestURL = RequestUtil.getRequestURL(request);
            String content = String.format("<h1>hello chendd URL = %1$s</h1>" , requestURL);
            response.getWriter().println(content);
        }

    }

}

运行截图

https.gif

(首页访问)

image.png

(启动输出http和https及对应端口号)

功能点说明

(1)服务器启动时输出支持的https和http协议以及端口号,端口号是由application.yaml配置文件中定义;

(2)server.port设置的443是https协议默认端口,配合启用https参数表示使用https协议访问;同时80端口是定制tomcat参数时指定的http协议端口,同时定制tomcat时有过滤器拦截所有的请求,将http协议自动转向至https协议对应的功能页面;

(3)上述运行示例的首页访问图中,访问的是http的地址,自动转向至对应的https地址;

(4)由于证数使用的www.chendd.cn域名,故运行示例时在host文件中将www.chendd.cn域名指向了localhost地址;

源码下载

源码工程下载可转至https://gitee.com/88911006/chendd-blog-examples项目的https分支;

 点赞


 发表评论

当前回复:作者

 评论列表


留言区