SpringBoot项目(Tomcat启动https端口)——springboot配置Tomcat两个端口,https和http的方式 & jar的打包和运行

这篇具有很好参考价值的文章主要介绍了SpringBoot项目(Tomcat启动https端口)——springboot配置Tomcat两个端口,https和http的方式 & jar的打包和运行。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

引出


1.springboot配置Tomcat两个端口,https和http的方式;
2.在https协议下,发送axios请求没反应,暂时用form表单解决;
3.运行jar包template might not exist报错及解决;

代码位置:
https://gitcode.net/Pireley/springboot-tomcat-http-https

springboot配置Tomcat两个端口,https和http的方式

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

1.生成SSL证书

严格来说https不是一个独立协议,只是在http协议基础上增加了SSL/TLS加密层。所以我们需要先生成SSL证书,这里使用keytool生成jks。

keytool -genkey -alias client -keypass 12345678 -keyalg RSA -keysize 2048 -validity 365 -storetype PKCS12 -keystore ./client.p12 -storepass 12345678

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

2.配置client.p12和https端口

server:
  ssl:
    key-store: classpath:client.p12
    key-store-password: 12345678
    key-store-type: PKCS12
    key-alias: client
  # https的访问端口
  port: 8443

3.配置http的8080端口WebServerFactoryCustomizer接口

WebServerFactory接口的几个重要实现:

  • TomcatServletWebServerFactory:对应于tomcat

  • JettyServletWebServerFactory:对应jetty

  • UndertowServletWebServerFactory:对应undertow

  • NettyReactiveWebServerFactory:对应netty

Spring Boot默认使用http/1.1协议。所以我们增加额外的自定义https连接器。

package com.shanxi.gis.config;

import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

@Component
public class TomcatServerCustomer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        final Connector httpConn = new Connector("HTTP/1.1");
        httpConn.setPort(8080);
        factory.addAdditionalTomcatConnectors(httpConn);
    }
}

4.启动项目

运行项目后可以看到启动了https的8843和http的8080两个端口

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

项目应用:在某项目中有一个功能需要https协议

Tomcat启动https和http两个端口

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

TomcatServerCustomer.java文件

package com.shanxi.gis.config;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

@Component
public class TomcatServerCustomer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Value("${ServerHttpPort}")
    Integer httpHost;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        final Connector httpConn = new Connector("HTTP/1.1");
        httpConn.setPort(httpHost);
        factory.addAdditionalTomcatConnectors(httpConn);
    }
}

application.yml配置文件

server:
  ssl:
    key-store: classpath:client.p12
    key-store-password: 12345678
    key-store-type: PKCS12
    key-alias: client
  # https的访问端口
  port: 8443

# 部署服务器的配置
ServerHttpsUrl: https://localhost:8443 # https的url
ServerHttpUrl: http://localhost:8080 # http的url
ServerHttpPort: 8080 # http的端口号
LoginPassword: Admin@1a2 # 登陆的密码


spring:
  mvc:
    static-path-pattern: /**
  resources:
    static-locations: classpath:/static/
  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    cache: false
    suffix: .html #模板后缀
    encoding: UTF-8 #编码
    mode: HTML #模板
    servlet:
      content-type: text/html

根据http或者https确定拦截后到哪个页面

LoginAuthorInterceptor.java文件

request.getScheme(); // for example, http, https, or ftp.

package com.shanxi.gis.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * spring的拦截器,
 * 1.在容器中,@Component
 * 2.是spring的拦截器 implements HandlerInterceptor
 */
@Component
public class LoginAuthorInterceptor implements HandlerInterceptor {

    @Value("${ServerHttpsUrl}")
    String httpsUrl;

    @Value("${ServerHttpUrl}")
    String httpUrl;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果没有登陆,就去登陆页面,如果登陆了就放行
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        System.out.println(user);
        if ("admin".equals(user)){
            return true;
        }else {
            // 没有登陆,就去登陆页面
            String scheme = request.getScheme(); // for example, http, https, or ftp.
            // 如果是http就去,http的端口
            if ("http".equals(scheme)){
                response.sendRedirect(httpUrl+"/user/loginPage");
            }
            // 否则就去https的端口
            response.sendRedirect(httpsUrl+"/user/loginPage");
            return false;
        }
    }
}

后端共享值,前端form表单获取

login.html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆页面</title>
    <link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
    <script src="/js/jquery-3.5.1.js"></script>
    <script src="/bootstrap/js/bootstrap.js"></script>
    <script src="/js/axios.min.js"></script>
    <script src="/js/vue.min-v2.5.16.js"></script>
    <link rel="stylesheet" href="/css/login.css">
</head>

<body>
    <div class="login-container" id="app">
        <h2>欢迎登录</h2>
<!--        "https://localhost:8443/user/login"-->
        <form :action=url method="post">
            <label for="username">用户名:</label>
            <input type="text" id="username" v-model="username" placeholder="请输入用户名" required name="username">
            <label for="password">密码:</label>
            <input type="password" id="password" v-model="password" placeholder="请输入密码" required name="password">
            <input type="submit" value="登录" @click="loginBtn" class="btn btn-primary btn-block">
        </form>
    </div>

<script>
    let app = new Vue({
        el:"#app",
        data:{
            username:"",
            password:"",
            url:"[[${httpsUrl}]]",
        },
        methods:{
        },
        created(){},
    })
</script>
</body>
</html>

后端共享值+跳转loginController.java

    @Value("${ServerHttpsUrl}")
    String httpsUrl;

    // 1.先到登陆页面
    @RequestMapping("/loginPage") // /user/loginPage
    public ModelAndView loginPage(){
        ModelAndView mv = new ModelAndView("user/login");
        mv.addObject("httpsUrl", httpsUrl + "/user/login");
        return mv;
    }

配置文件设置url

server:
  ssl:
    key-store: classpath:client.p12
    key-store-password: 12345678
    key-store-type: PKCS12
    key-alias: client
  # https的访问端口
  port: 8443

# 部署服务器的配置
ServerHttpsUrl: https://localhost:8443 # https的url
ServerHttpUrl: http://localhost:8080 # http的url
ServerHttpPort: 8080 # http的端口号
LoginPassword: Admin@1a2 # 登陆的密码


spring:
  mvc:
    static-path-pattern: /**
  resources:
    static-locations: classpath:/static/
  thymeleaf:
    prefix: classpath:/templates/
    check-template-location: true
    cache: false
    suffix: .html #模板后缀
    encoding: UTF-8 #编码
    mode: HTML #模板
    servlet:
      content-type: text/html

问题:在https协议下,发送axios请求没反应

问题如下:

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

解决方案一:用form表单

后端,用户名和密码正确后,重定向到index.html页面

// form表单下重定向到indexPage页面
response.sendRedirect(httpsUrl+“/user/indexPage”);

package com.shanxi.gis.controller;

import com.shanxi.gis.entity.ResData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@Controller
@RequestMapping("/user")
@CrossOrigin // 允许跨域
public class LoginController {
    @Value("${ServerHttpsUrl}")
    String httpsUrl;

    @Value("${LoginPassword}")
    String loginPassword;

    // 1.先到登陆页面
    @RequestMapping("/loginPage") // /user/loginPage
    public ModelAndView loginPage(){
        ModelAndView mv = new ModelAndView("user/login");
        mv.addObject("httpsUrl", httpsUrl + "/user/login");
        return mv;
    }

    // 2.处理前端的axios请求
    @Autowired
    HttpSession session; // TODO:保存用户名到session

    @RequestMapping("/login")
    @ResponseBody
    public ResData login(
            String username,
            String password, HttpServletResponse response
            ) throws IOException {
        System.out.println(username +"//"+ password);
        if (Objects.equals(username, "") || username==null ||
                Objects.equals(password, "") || password==null
        ){
            return new ResData(1001, "必填项为空", null);
        }

        if (!"admin".equals(username) || !loginPassword.equals(password)){
            return new ResData(1002, "用户名|密码错误", null);
        }
        session.setAttribute("user",username); // TODO:set进session
        // form表单下重定向到indexPage页面
        response.sendRedirect(httpsUrl+"/user/indexPage");

        return new ResData(200, "ok", null);
    }

    // 3.登陆成功到index页面
    @RequestMapping("/indexPage")
    public String loginIndex(){
        return "gis/index";
    }
}

前端发送form表单

<form :action=url method=“post”>

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登陆页面</title>
    <link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
    <script src="/js/jquery-3.5.1.js"></script>
    <script src="/bootstrap/js/bootstrap.js"></script>
    <script src="/js/axios.min.js"></script>
    <script src="/js/vue.min-v2.5.16.js"></script>
    <link rel="stylesheet" href="/css/login.css">
</head>

<body>
    <div class="login-container" id="app">
        <h2>欢迎登录</h2>
<!--        "https://localhost:8443/user/login"-->
        <form :action=url method="post">
            <label for="username">用户名:</label>
            <input type="text" id="username" v-model="username" placeholder="请输入用户名" required name="username">
            <label for="password">密码:</label>
            <input type="password" id="password" v-model="password" placeholder="请输入密码" required name="password">
            <input type="submit" value="登录" @click="loginBtn" class="btn btn-primary btn-block">
        </form>
    </div>

<script>
    let app = new Vue({
        el:"#app",
        data:{
            username:"",
            password:"",
            url:"[[${httpsUrl}]]",
        },
        methods:{
            loginBtn(){
                console.log("send----")
                let params = new URLSearchParams();
                params.append("username",this.username)
                params.append("password",this.password)
                // axios.post("/user/login",params)
                axios.post("/user/login",params)
                    .then(response=>{
                        console.log("axios")
                        if (response.data.code==200){
                            // alert("登陆成功")
                            location.href= "/user/indexPage"
                        }else {
                            alert(response.data.msg)
                        }
                    })
            }
        },
        created(){},
    })

</script>

</body>
</html>

项目的打包部署

1.template might not exist or might not be accessible by any of the configured Template Resolvers

错误描述:

在idea中进行测试,所有功能都可以实现,尝试打包成jar包后运行,进入首页后没有显示用户信息页面,报500异常,后台显示Error resolving template [/user/info], template might not exist or might not be accessible by any of the configured Template Resolvers

报错信息:

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

2023-07-08 10:16:11.298 ERROR 28396 — [p-nio-80-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/user/info], template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/user/info], template might not exist or might not be accessible by any of the configured Template Resolvers

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

解决方案一:

@RequestMapping("/infoPage")
public String infoPage(){
    return "/user/info";
}

跳转页面去掉第一个反斜杠,改为如下

    @RequestMapping("/infoPage")
    public String infoPage(){
        return "user/info";
    }

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https

thymeleaf + Spring Boot 在开发环境正常,但用jar运行时报错 Error resolving template template might not exist or might not be accessible;

就可以了

解决方案二:

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

改成

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates
spring.thymeleaf.suffix=.html
## spring相关的配置
spring:
  # 连接数据库
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/javaweb?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    username: root
    password: 123
  ## 设置上传文件大小
  servlet:
    multipart:
      max-file-size: 10MB # 设置单个文件最大大小为10MB

  # 另一种解决方案
  thymeleaf:
    cache: false
    prefix: classpath:/templates
    suffix: .html

此时所有跳页面的都要加反斜杠

springboot启动两个端口,SpringBoot,http,spring boot,tomcat,https文章来源地址https://www.toymoban.com/news/detail-768299.html

到了这里,关于SpringBoot项目(Tomcat启动https端口)——springboot配置Tomcat两个端口,https和http的方式 & jar的打包和运行的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 34、springboot切换内嵌Web服务器(Tomcat服务器)与 生成SSL证书来把项目访路径从 HTTP 配置成 HTTPS

    知识点1:springboot切换内嵌Web服务器(Tomcat服务器) 知识点2:生成SSL证书来把项目访路径从 HTTP 配置成 HTTPS spring-boot-starter-web 默认依赖 Tomcat 内置服务器 改为 Jetty 服务器 改为 Undertow 服务器 目的:把请求路径 http://xxxxx 改成 https://xxxxx 如图:原本普通的项目,启动后是http的

    2024年02月11日
    浏览(41)
  • SpringBoot项目 Tomcat部署war程序时启动成功但是访问404异常处理

    Springboot项目 使用IntelliJ IDEA 将maven项目打war包,pom.xml文件中引入了依赖 并通过maven的package打包完后,放入tomcat的web-apps文件下 同时修改了打开conf文件夹下的server.xml文件,启动tomcat时出现了以下问题 SpringApplicationBuilder用于构建 Spring 应用,是SpringApplication和ApplicationContext实例

    2024年02月14日
    浏览(36)
  • [bug日志]springboot多模块启动,在yml配置启动端口8081,但还是启动了8080

    【问题描述】 配置的启动端口是8081,实际启动端口是8080 【解决方法】 1.检查application.yml的配置是否有错误(配置项中,显示白色就错,橙色无措) 2.检查pom.xml的打包方式配置项配置,主pom.xml中的配置项一般为:packagingpom/packaging,模块中的配置项目为:packagingjar/packaging 3.然后

    2024年02月11日
    浏览(25)
  • springboot 项目启动后,localhost加端口可以访问,但是外网IP不行

    现象 java springboot项目启动后,localhost(或127.0.0.1)加端口可以访问,但是使用外网IP却无法访问。 原因及解决方法 springboot 的配置文件(yml 或 properties) 中缺少 server.address 的设置。 解决方法: 在springboot 的配置文件中增加 server.address 的配置。yml 配置文件如下所示: server.ad

    2024年02月16日
    浏览(31)
  • SpringBoot2.0(Spring读取配置文件常用方法,打war包在Tomcat中启动)

    在springBoot声明周期内,可以使用@Value注解从SpringBoot的默认配置文件中读取配置信息 例如在Controller中使用: @Value可以放到属性或方法上,能够正常使用的前提是所在类,必须在SpringBoot的生命周期内。 我们怎么把一个类放到Spring的生命周期中进行管理?使用的是@Component注解

    2024年02月09日
    浏览(39)
  • 配置https ssl elasticsearch,springboot项目中连接elasticsearch https

    参考之前的文章 创建self-signed证书 下面展示一些 内联代码片 。 启动springboot项目应该可以连接上elasticsearch了。

    2024年02月11日
    浏览(30)
  • VSCode配置启动springboot项目

    本人前一段时间使用intellij,发现配置较为复杂,于是尝试用VSCode配置,发现比intellij稍方便些。写下记录以便个人往后用。 JDK下载链接:https://www.oracle.com/cn/java/technologies/downloads/#jdk20-windows 选择x64 Installer下载并安装 Maven下载链接:https://maven.apache.org/download.cgi 选择Binary zip

    2024年02月16日
    浏览(28)
  • springboot前后端分离项目配置https接口(ssl证书)

    本记录操作方法vue.js项目使用nginx代理部署,后端springboot正常部署 前端使用443端口,后端使用8080端口 全部接口使用https vue.js配置axios相对路径,好处:请求代理再nginx.conf中配置,无需重新修改代码 request和response 拦截器根据具体项目要求进行配置 在/usr/front/vue下创建Dockerf

    2024年02月03日
    浏览(32)
  • Nginx配置springboot+vue项目http跳转https

    java生成证书 添加依赖 复制keystore到springboot资源目录,修改application.yml配置  启动项目 nginx配置 开启ssl     重启nginx -s reload 访问localhost:81将跳转到https://localhost/login?redirect=/index  

    2024年02月12日
    浏览(34)
  • 31、springboot 配置HTTP服务端口及如何通过WebServer实例动态获取项目中的HTTP端口

    代码示例 就是在yml配置文件中配置端口号 代码演示 需求:在项目中获取服务器的动态端口,通过获取WebServer实例来获取动态端口号。 **获取WebServer实例的方法1:**通过WebServerApplicationContext来获取WebServer 获取WebServer实例的方法2: 实现一个监听器接口:ApplicationListener 来获取

    2024年02月12日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包