背景
开发过程中遇到在请求参数中添加特殊字符导致请求报错的问题,特记录一下。
解决
问题复现
代码:
一个简单的 get 请求。
@GetMapping("/t3")
public String test3(@RequestParam String s){
return s;
}
POSTMAN 调用:
服务端的日志:
java.lang.IllegalArgumentException: Invalid character found in the request target [/t3?s={langjialing}]. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:490) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:261) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:888) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.41.jar:9.0.41]
at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
问题解决
此问题是由于 Tomcat 新版本中添加了 URL 的特殊字符校验,在配置文件中添加相应的配置即可。
例如我们在 application.yaml
文件中进行配置:
server:
tomcat:
relaxed-path-chars:
- '{'
- '}'
- '['
- ']'
relaxed-query-chars:
- '{'
- '}'
- '['
- ']'
总结
此问题为新版本 Tomcat 增加了对 URL 中特殊字符的校验导致的问题,在 Spring 的配置文件中增加相应的配置即可解决。