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的方式

在这里插入图片描述

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

在这里插入图片描述

在这里插入图片描述

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两个端口

在这里插入图片描述

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

Tomcat启动https和http两个端口

在这里插入图片描述

在这里插入图片描述

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请求没反应

问题如下:

在这里插入图片描述

解决方案一:用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

报错信息:

在这里插入图片描述

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

在这里插入图片描述

解决方案一:

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

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

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

在这里插入图片描述

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

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

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Spring Boot项目配置Tomcat可以通过以下步骤实现: 1. 在pom.xml文件中添加Tomcat依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> ``` 2. 在application.properties文件中配置Tomcat端口号: ``` server.port=808 ``` 3. 在启动类中添加@EnableAutoConfiguration注解: ``` @SpringBootApplication @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 4. 打包项目运行: ``` mvn clean package java -jar target/myproject.jar ``` 以上就是Spring Boot项目配置Tomcat的简单步骤。 ### 回答2: Spring Boot 是一个基于 Spring 框架的快速开发框架,能够非常简便地创建独立的、生产级别的、基于 Spring 的应用程序。当需要将 Spring Boot 应用程序部署到生产环境中时,我们可以将其打包成 war 包或 jar 包,再配置 Tomcat 作为应用程序的 Web 服务器。 首先,在 pom.xml 文件中引入 Spring Boot 的 web 运行时依赖项,即: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> ``` 然后,在应用程序的主类上添加注解 `@EnableAutoConfiguration` 和 `@SpringBootApplication`。如下: ``` @SpringBootApplication @EnableAutoConfiguration public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` 接着,我们可以在 `application.properties` 或 `application.yml` 中进行相关配置,例如: ``` server.port=8081 server.context-path=/myapp ``` 以上配置Tomcat 服务器端口号设置为 8081,同时将应用程序部署到 http://localhost:8081/myapp。 最后,使用 Maven 命令将应用程序打包成 war 包,例如: ``` mvn clean package ``` 打包完成后,将 war 包复制到 Tomcat 服务器的 webapps 目录下,并启动 Tomcat 即完成项目的部署。 总结:Spring Boot 配置 Tomcat 可以通过引入 web 运行时依赖项、添加启动注解、配置服务器相关属性等操作,最终通过 Maven 命令打包成 war 包部署到 Tomcat 服务器中。 ### 回答3: Spring Boot是一个非常流行的Java Web应用程序框架,它简化了开发者在创建和部署Web应用程序时所需的步骤。Spring Boot支持使用嵌入式web服务器(如Tomcat,Jetty,Undertow等)运行应用程序,也支持将应用程序打成war包并在外部web服务器上运行。本文将详细介绍如何在Spring Boot项目配置Tomcat服务器。 1.添加Tomcat依赖 在Spring Boot项目的pom.xml文件中添加Tomcat依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> ``` 2.配置Tomcat连接器 在application.properties文件中配置Tomcat连接器: ``` server.port=8080 server.tomcat.max-connections=200 server.tomcat.max-threads=100 server.tomcat.uri-encoding=UTF-8 ``` 上述配置中,我们指定了Tomcat服务器的端口、最大连接数、最大线程数、编码方式。 3.构建war包 如果想要将应用程序部署到外部Tomcat服务器上,则需要将应用程序打成war包。在pom.xml文件中添加如下配置: ``` <packaging>war</packaging> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ``` 上述配置中,我们指定了打包方式为war,并添加了spring-boot-maven-plugin插件来打包应用程序。 4.部署war包 将打包好的war包复制到外部tomcat服务器的webapps目录下,并启动Tomcat服务器,即可部署应用程序。 最后,通过以上步骤我们已经成功配置Tomcat服务器并将应用程序部署到了外部Tomcat服务器上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Perley620

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值