JAVA Spring BootURL 忽略大小写
JAVA Spring Boot开发中。默认URL是区分大小写的
🎯 1. 遵循 HTTP 标准与框架一致性
HTTP 协议对路径的大小写本身是区分的:
GET /api/user
≠GET /API/USER
(从服务器角度看是两个资源)类似于文件系统中
/Users/Alice
和/users/alice
,很多服务器都区分这些路径
Spring 作为一个企业级框架,默认行为要遵循规范,而不是“对开发者友好”优先。
🎯 2. 与文件系统、路由分发的语义一致
在很多部署环境中:
Linux 是大小写敏感的文件系统
Java 包名、类名也区分大小写
一些 API Gateway(如 Nginx、Kong)也是默认区分大小写的
所以 Spring 选择了默认大小写敏感,以避免路径匹配出现歧义或不一致。
🎯 3. 安全和设计语义考虑
路径大小写可能会被有意“混淆”使用。例如:
Markup 全选
/api/adminUser ✅ 正常用户接口
/API/AdminUser ❌ 试图伪装成另一个接口
默认敏感,能避免路由重名、绕过安全配置的问题。
🧠 举个例子:
Markup 全选
@GetMapping("/login")
public String login() {}
@GetMapping("/Login")
public String adminLogin() {}
这在大小写敏感情况下是两个不同接口,你可以明确地设计它们。而如果默认忽略大小写,就会导致冲突或抛错。
解决办法 Spring Boot 2.6+
通过 PathPatternParser 设置全局路由匹配忽略大小写,这种方式 简洁、官方支持、不会干扰其他配置。
创建一个配置类 WebConfig.java:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
PathPatternParser parser = new PathPatternParser();
parser.setCaseSensitive(false); // 👈 设置为不区分大小写
configurer.setPatternParser(parser);
}
}
解决办法 Spring Boot 2.3.7
Spring Boot 2.3.7,这个版本还不支持 PathPatternParser,只能使用 AntPathMatcher 的方式来设置路由大小写不敏感。
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
AntPathMatcher matcher = new AntPathMatcher();
matcher.setCaseSensitive(false); // 👈 设置忽略大小写
configurer.setPathMatcher(matcher);
}
}
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 张国生