Java EE 进阶:SpringBoot 配置⽂件

devtools/2025/3/13 16:31:27/

什么是配置文件

“配置文件”是一个用来保护程序或者系统设置信息的文件,它的作用是让程序在启动或者运行中,能够读取这些设置并按预期进行工作,而不需要手动的设置。

Spring Boot 配置文件

  • 设置服务器端口、编码格式
  • 配置数据库连接
  • 控制日志级别
  • 设置缓存、邮件、消息队列等服务参数
  • 管理不同环境(开发、测试、生产)下的配置

Spring Boot中的配置文件一共有两种形式

.properties文件 和  .yml  /.yaml文件

properties 基本语法

properties 是以键值的形式配置的,key和value之间是以"="连接的

java">spring.application.name=spring-ioc demo
server.port=8081spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root#自定义
my.key=10
my.key2=true

 

yml基本语法

yml是树形结构的配置⽂件,它的基础语法是"key:value"

记住:在key:value中“ :”后一定要加空格

java">server:port: 8081my:key: 11spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=falsespring:datasource:url: jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=falseusername: adminpassword: 123456#自定义的key
aa.bb.cc=5
aa.bb.dd=6
aa.bb.cc: 5
aa.bb.dd: 6#字符串
string.value: hello#布尔值,true/false
boolean.value: false
boolean.value1: true#整数
int.value: 12#浮点数
float.value: 12.12#Null,~代表Null
null.value: ~"" 空字符串
empty.value: ''
#里面什么都不用写

yml的配置读取

用@value注解和@ConfigurationProperties注解来读取文件

两个注解的区别:@value注解用于读取单个配置项,@ConfigurationProperties注解用于批量注入多个配置项

@value注解

java">@Controller
public class YmlController {@Value("${my.key3}")private String myKey3;@Value("${my.key4}")private String myKey4;@PostConstructpublic void print(){System.out.println(myKey3);System.out.println(myKey4);}
}
java">my:key3: Hellokey4: 5

 

@ConfigurationProperties注解

集合和Map的配置

java">@Data
@ConfigurationProperties(prefix = "dbtypes")
@Component
public class DbTypes {private Integer id;private List<String> name;private Map<String,String> ball;
}@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {private Integer id;private String name;private Integer age;
}
java">@Controller
public class YmlController {@Autowiredprivate Person person;@Autowiredprivate DbTypes dbTypes;@PostConstructpublic void print(){System.out.println(person);System.out.println(dbTypes);}
}

在yml配置文件中

java">person:id: 1name: zhangsanage: 15dbtypes:id: 4name:- 123- sa- ssball:k1: v1k2: v2k3: v3

 

yml的优缺点:

优点

1.结构清晰,一目了然 

 2.支持复杂数据类型(List、Map 等)

3.语法简洁,没有重复前缀

4.可读性强

 

缺点

1.缩进必须正确,容易出错

2.不适合写大量注释

3.调试时不容易发现问题

验证码案例

随着安全性的要求越来越⾼,⽬前项⽬中很多都使⽤了验证码,验证码的形式也是多种多样,更复杂的图 形验证码和⾏为验证码已经成为了更流⾏的趋势。

我们通过Hutool提供的小工具来实现验证码

需求:

在页面上生成验证码图案,然后通过输入验证码图形输入正确的验证码通过验证。

首先我们打开Hutool,找到图形验证码

 

操作流程:

导入包,引入依赖

java">        <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency>

 首先我们先生成验证码

我们生成的是圆圈干扰图形的验证码

java"> CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(),captchaProperties.getLength());String code=captcha.getCode();

由于用户输入完验证码,我们需要对比是否输入正确,所以我们需要得到正确的验证码,所以我们需要在生成验证码后,将正确的验证码存到Session中

java">     session.setAttribute(captchaProperties.getSession().getKey(),code);session.setAttribute(captchaProperties.getSession().getDate(),new Date());captcha.write(response.getOutputStream());

然后我们需要进行一个校验 ,判断用户输入的验证码是否正确

java">if (StringUtil.isNullOrEmpty(captcha)){return false;}String code =(String) session.getAttribute(captchaProperties.getSession().getKey());Date date =(Date) session.getAttribute(captchaProperties.getSession().getDate());if(captcha.equalsIgnoreCase(code) && date!=null  && System.currentTimeMillis()-date.getTime()<VALID_TIME){return true;}return false;

我们将图形的大小写入配置文件中

java">captcha:width: 150length: 100session:key: CAPTCHA_SESSION_KEYdate: CAPTCHA_SESSION_DATE

并且用户在输入验证码时有时间限制,超过了一定的时间,就会失效,所以我们需要定义一段时间限制

一分钟

java">private final static Long VALID_TIME=60*30*1000L;

系统现在的时间 - 输入开始的时间 < 一分钟  

java">System.currentTimeMillis()-date.getTime()<VALID_TIME

然后在前端代码中写入接口

javascript"> $.ajax({type:"post",url:"/captcha/check",data:{captcha:$("#inputCaptcha").val()},success:function(result){if(result){location.href="success.html";}else{alert("输入失败,请重新输入");}}

并且在前段代码中写入

  <meta charset="utf-8"><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /><meta http-equiv="Pragma" content="no-cache" /><meta http-equiv="Expires" content="0" />

它们用于防止浏览器缓存网页内容,确保每次都从服务器加载最新资源(特别适合验证码、表单、动态页面等场景)。 

演示效果如下:

输入错误的验证码

输入正确的验证码

 

 

后端代码

CaptchaProperties
java">@Data
@ConfigurationProperties(prefix = "captcha")
@Configuration
public class CaptchaProperties {private Integer width;private Integer length;private Session session;@Datapublic static class Session {private String key;private String date;}
}
CaptchaController
java">package com.blame.springcaptcha.captcahController;import ch.qos.logback.core.util.StringUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.blame.springcaptcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Date;@RequestMapping("captcha")
@RestController
public class CaptchaController {@Autowiredprivate CaptchaProperties captchaProperties;private final static Long VALID_TIME=60*30*1000L;@RequestMapping("/getCaptcha")public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {response.setContentType("image/jpeg");CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(),captchaProperties.getLength());String code=captcha.getCode();session.setAttribute(captchaProperties.getSession().getKey(),code);session.setAttribute(captchaProperties.getSession().getDate(),new Date());captcha.write(response.getOutputStream());}@RequestMapping("/check")public boolean check(HttpSession session,String captcha){if (StringUtil.isNullOrEmpty(captcha)){return false;}String code =(String) session.getAttribute(captchaProperties.getSession().getKey());Date date =(Date) session.getAttribute(captchaProperties.getSession().getDate());if(captcha.equalsIgnoreCase(code) && date!=null  && System.currentTimeMillis()-date.getTime()<VALID_TIME){return true;}return false;}}

.yml文件

java">spring:application:name: Spring-captchacaptcha:width: 150length: 100session:key: CAPTCHA_SESSION_KEYdate: CAPTCHA_SESSION_DATE

 

 前端代码

index.html

<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" /><meta http-equiv="Pragma" content="no-cache" /><meta http-equiv="Expires" content="0" /><title>验证码</title><style>#inputCaptcha {height: 30px;vertical-align: middle; }#verificationCodeImg{vertical-align: middle; }#checkCaptcha{height: 40px;width: 100px;}</style>
</head><body><h1>输入验证码</h1><div id="confirm"><input type="text" name="inputCaptcha" id="inputCaptcha"><img id="verificationCodeImg" src="/captcha/getCaptcha" style="cursor: pointer;" title="看不清?换一张" /><input type="button" value="提交" id="checkCaptcha"></div><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script><script>$("#verificationCodeImg").click(function(){$(this).hide().attr('src', '/captcha/getCaptcha?dt=' + new Date().getTime()).fadeIn();});$("#checkCaptcha").click(function () {$.ajax({type:"post",url:"/captcha/check",data:{captcha:$("#inputCaptcha").val()},success:function(result){if(result){location.href="success.html";}else{alert("输入失败,请重新输入");}}})});</script>
</body></html>

success.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>验证成功页</title>
</head>
<body><h1>验证成功</h1>
</body>
</html>

 

希望能对大家有所帮助!!!!

 

 

 


http://www.ppmy.cn/devtools/166816.html

相关文章

深入解析pnpm与npm:颠覆传统包管理的技术革命与应用实践

深入解析pnpm与npm&#xff1a;颠覆传统包管理的技术革命与应用实践 引言&#xff1a;被node_modules支配的恐惧 "你的node_modules有多大&#xff1f;"这个灵魂拷问总能引发开发者会心一笑。当项目规模达到500MB时&#xff0c;npm install需要喝三杯咖啡的时间&am…

每日OJ_牛客_过桥_贪心+BFS_C++_Java

目录 牛客_过桥_贪心BFS 题目解析 C代码 Java代码 牛客_过桥_贪心BFS 过桥 描述&#xff1a; dd被困在了一个迷幻森林&#xff0c;现在她面前有一条凶险的大河&#xff0c;河中央有n个神奇的浮块&#xff0c;浮块按1∼n1顺序标号&#xff0c;但两两并不相接&…

Spring Boot拦截器(Interceptor)详解

拦截器Interceptor 拦截器我们主要分为三个方面进行讲解&#xff1a; 介绍下什么是拦截器&#xff0c;并通过快速入门程序上手拦截器拦截器的使用细节通过拦截器Interceptor完成登录校验功能 1. 快速入门 什么是拦截器&#xff1f; 是一种动态拦截方法调用的机制&#xff…

Python Selenium库入门使用,图文详细。附网页爬虫、web自动化操作等实战操作。

文章目录 前言1 创建conda环境安装Selenium库2 浏览器驱动下载&#xff08;以Chrome和Edge为例&#xff09;3 基础使用&#xff08;以Chrome为例演示&#xff09;3.1 与浏览器相关的操作3.1.1 打开/关闭浏览器3.1.2 访问指定域名的网页3.1.3 控制浏览器的窗口大小3.1.4 前进/后…

【华为OD机考真题】- 星际篮球争霸赛(Java)

1. 题目描述 具体题目描述如下&#xff1a; 在星球争霸篮球赛对抗赛中&#xff0c;最大的宇宙战队希望每个人都能拿到 MVP&#xff0c;MVP 的条件是单场最高分得分获得者。 可以并列&#xff0c;所以宇宙战队决定在比赛中&#xff0c;尽可能让更多队员上场,并且让所有得分的选手…

Ubuntu-配置apt国内源

Ubuntu-配置apt国内源 安装vim apt-get update apt-get install -y vim备份 cp /etc/apt/sources.list /etc/apt/sources.list.bak编辑源数据 vim /etc/apt/sources.list deb http://mirrors.aliyun.com/ubuntu/ jammy main restricted universe multiverse deb-src http://m…

信息安全意识之安全组织架构图

一、信息安全技术概论1.网络在当今社会中的重要作用2.信息安全的内涵 网络出现前&#xff1a;主要面向数据的安全&#xff0c;对信息的机密性、完整性和可用性的保护&#xff0c;即CIA三元组 网络出现后&#xff0c;还涵盖了面向用户的安全&#xff0c;即鉴别&#xff0c;授权&…

OpenHarmony-SELinux配置

前言&#xff1a; OpenHarmony 上某个进程向samgr注册SA服务&#xff0c;其他进程在与该进程进行IPC通信之前&#xff0c;需要获取该SA服务&#xff0c;SA提供方需要为该SA配置SELinux标签&#xff0c;否则该SA会被SELinux配置为u:object_r:default_service:s0标签&#xff0c…