Java EE 进阶:SpringBoot 配置⽂件
什么是配置文件
“配置文件”是一个用来保护程序或者系统设置信息的文件,它的作用是让程序在启动或者运行中,能够读取这些设置并按预期进行工作,而不需要手动的设置。
Spring Boot 配置文件
- 设置服务器端口、编码格式
- 配置数据库连接
- 控制日志级别
- 设置缓存、邮件、消息队列等服务参数
- 管理不同环境(开发、测试、生产)下的配置
Spring Boot中的配置文件一共有两种形式
.properties文件 和 .yml /.yaml文件
properties 基本语法
properties 是以键值的形式配置的,key和value之间是以"="连接的
spring.application.name=spring-ioc demo
server.port=8081
spring.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中“ :”后一定要加空格
server:
port: 8081
my:
key: 11
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=false
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=false
username: admin
password: 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注解
@Controller
public class YmlController {
@Value("${my.key3}")
private String myKey3;
@Value("${my.key4}")
private String myKey4;
@PostConstruct
public void print(){
System.out.println(myKey3);
System.out.println(myKey4);
}
}
my:
key3: Hello
key4: 5
@ConfigurationProperties注解
集合和Map的配置
@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;
}
@Controller
public class YmlController {
@Autowired
private Person person;
@Autowired
private DbTypes dbTypes;
@PostConstruct
public void print(){
System.out.println(person);
System.out.println(dbTypes);
}
}
在yml配置文件中
person:
id: 1
name: zhangsan
age: 15
dbtypes:
id: 4
name:
- 123
- sa
- ss
ball:
k1: v1
k2: v2
k3: v3
yml的优缺点:
优点
1.结构清晰,一目了然
2.支持复杂数据类型(List、Map 等)
3.语法简洁,没有重复前缀
4.可读性强
缺点
1.缩进必须正确,容易出错
2.不适合写大量注释
3.调试时不容易发现问题
验证码案例
随着安全性的要求越来越⾼,⽬前项⽬中很多都使⽤了验证码,验证码的形式也是多种多样,更复杂的图 形验证码和⾏为验证码已经成为了更流⾏的趋势。
我们通过Hutool提供的小工具来实现验证码
需求:
在页面上生成验证码图案,然后通过输入验证码图形输入正确的验证码通过验证。
首先我们打开Hutool,找到图形验证码
操作流程:
导入包,引入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
首先我们先生成验证码
我们生成的是圆圈干扰图形的验证码
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(),captchaProperties.getLength());
String code=captcha.getCode();
由于用户输入完验证码,我们需要对比是否输入正确,所以我们需要得到正确的验证码,所以我们需要在生成验证码后,将正确的验证码存到Session中
session.setAttribute(captchaProperties.getSession().getKey(),code);
session.setAttribute(captchaProperties.getSession().getDate(),new Date());
captcha.write(response.getOutputStream());
然后我们需要进行一个校验 ,判断用户输入的验证码是否正确
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;
我们将图形的大小写入配置文件中
captcha:
width: 150
length: 100
session:
key: CAPTCHA_SESSION_KEY
date: CAPTCHA_SESSION_DATE
并且用户在输入验证码时有时间限制,超过了一定的时间,就会失效,所以我们需要定义一段时间限制
一分钟
private final static Long VALID_TIME=60*30*1000L;
系统现在的时间 - 输入开始的时间 < 一分钟
System.currentTimeMillis()-date.getTime()<VALID_TIME
然后在前端代码中写入接口
$.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
@Data
@ConfigurationProperties(prefix = "captcha")
@Configuration
public class CaptchaProperties {
private Integer width;
private Integer length;
private Session session;
@Data
public static class Session {
private String key;
private String date;
}
}
CaptchaController
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 {
@Autowired
private 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文件
spring:
application:
name: Spring-captcha
captcha:
width: 150
length: 100
session:
key: CAPTCHA_SESSION_KEY
date: 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>
希望能对大家有所帮助!!!!