springboot中报错Invalidcharacterfoundintherequest的解决
解决Invalid character found in the request问题
Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
原因
springBoot 2.0.0 以上都采用内置Tomcat8.0以上版本,而tomcat8.0以上版本遵从RFC规范添加了对Url的特殊字符的限制,url中只允许包含英文字母(a-zA-Z)、数字(0-9)、-_.~四个特殊字符以及保留字符( ! * ’ ( ) ; : @ & = + $ , / ? # [ ] ) (262+10+4+18=84)这84个字符,请求中出现了{}大括号或者[],所以tomcat报错。
设置RelaxedQueryChars允许此字符(建议),设置requestTargetAllows选项(Tomcat 8.5中不推荐)。
根据Tomcat文档,下面提供一种方法来设置松弛的QueryChars属性*
在启动类中添加
@Bean
public ConfigurableServletWEBServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
@Override
public void customize(Connector connector) {
connector.setProperty("relaxedQueryChars", "|{}[]");
}
});
return factory;
}
springboot项目报错问题
java.lang.IllegalArgumentException:Invalid character found in the request target.
原因
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
高版本tomcat中的新特性:就是严格按照 RFC 3986规范进行访问解析,而 RFC 3986规范定义了Url中只允许包含英文字母(a-zA-Z)、数字(0-9)、-_.~4个特殊字符以及所有保留字符(RFC3986中指定了以下字符为保留字符:! * ’ ( ) ; : @ & = + $ , / ? # [ ])。
springboot默认集成了tomcat,tomcat然后当你前端发送请求,请求参数中有保留的特殊字符时,就会报如下错
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.Http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:472)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:683)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NIOEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
有两种解决方法
- 一种降低tomcat版本(不建议),这里就不写了
- 另一种是在SpringBoot中增加tomcat配置
在config中新建一个TomcatConfig类
@Configuration
public class TomcatConfig {
@Bean
public TomcatServletWebServerFactory webServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers((Connector connector) -> {
connector.setProperty("relaxedPathChars", "\"<>[\\]^`{|}");
connector.setProperty("relaxedQueryChars", "\"<>[\\]^`{|}");
});
return factory;
}
}
然后重启项目测试,问题解决
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
相关文章