记录一个升级spring boot 版本从2.1升级到2.6之后的错误:
java.lang.IllegalArgumentException: Invalid contextPath '/admin': must match the start of requestPath: '//admin/init'
at org.springframework.http.server.DefaultRequestPath.validateContextPath(DefaultRequestPath.java:81)
at org.springframework.http.server.DefaultRequestPath.initContextPath(DefaultRequestPath.java:56)
这里contextPath的值 '/admin’是我的应用server.servlet.context-path配置
requestPath的值 '//admin/init’是我的请求url。
其实问题很简单,报错意思也清楚,就是请求路径中和contextPath不匹配,为啥之前好好的,升级版本后报错,应该是升级后检查更严格了
具体代码在org.springframework.http.server.DefaultRequestPath#validateContextPath方法中
private static void validateContextPath(String fullPath, String contextPath) {
int length = contextPath.length();
if (contextPath.charAt(0) == '/' && contextPath.charAt(length - 1) != '/') {
if (!fullPath.startsWith(contextPath)) {
throw new IllegalArgumentException("Invalid contextPath '" + contextPath + "': must match the start of requestPath: '" + fullPath + "'");
} else if (fullPath.length() > length && fullPath.charAt(length) != '/') {
throw new IllegalArgumentException("Invalid contextPath '" + contextPath + "': must match to full path segments for requestPath: '" + fullPath + "'");
}
} else {
throw new IllegalArgumentException("Invalid contextPath: '" + contextPath + "': must start with '/' and not end with '/'");
}
}
这里会检查请求的url是不是以context-path开头。
解决这个错误很简单,在我的例子里把多余的“/”去掉就好了。我是因为用nginx代理,配置转发,多配置了一个“/”。大家可以自己检查请求中为何多了一个“/”,或者其他原因导致的不匹配。
检查更严格总是好的,正确的事情只有一种做法,反而能省不少事!