【问题标题】:Spring Boot does not accept list params enclosed in bracketsSpring Boot 不接受括号中的列表参数
【发布时间】:2020-06-14 05:15:14
【问题描述】:

我有以下极其简单的SpringBoot程序

// APIEndpoints.java

// Imports!

public class APIEndpoints {
    @PostMapping("deduplicate")
    public String deduplicate(@RequestParam(value = "data") String data) {
        return data;
    }
}
// RestServiceApplication.java

@SpringBootApplication
public class RestServiceApplication {

    public static void main(String[] args) throws SQLException {
        SpringApplication.run(RestServiceApplication.class, args);
    }
}

我可以通过./gradlew bootRun启动springboot服务器,并且已经验证该服务器正在通过其他端点工作。

这是我的问题:使用邮递员发送帖子请求,以下顺利进行

localhost:8080/deduplicate?data=1,23,4,5

但是,这个失败并出现错误:“HTTP 400: Bad Request”

localhost:8080/deduplicate?data=[1,23,4,5]

这似乎是不受欢迎的行为,它doesn't seem to be 是 url 格式或类似内容的基本限制。

是什么导致了这个错误,如何设置 Spring Boot 以接受括号中的列表?

【问题讨论】:

  • 邮递员编码括号了吗?
  • 不确定你的意思,但我帖子中显示的文字正是我在 Postman 中输入的内容

标签: java json spring spring-boot rest


【解决方案1】:

要么

去重?data=1,23,4,5

重复数据删除?data=1&data=23&data=4&data=5

如果您想通过 REST API 作为请求参数作为数组,这就是它的工作原理。

【讨论】:

    【解决方案2】:

    您在 url 中使用了不安全的字符,因此您遇到了麻烦。 RFC1738

    " < > # % { } | \ ^ ~ [ ] ` including the blank/empty space.
    

    【讨论】:

      【解决方案3】:

      所以得到这个错误的主要原因是字符“[”和“]”。此答案中有关 URL 和 URI 允许字符的更多详细信息:Which characters make a URL invalid?

      最好的方式(遵循标准)——在客户端对 URL 进行编码:

      encodeURL("localhost:8080/deduplicate?data=[1,23,4,5]")
      >localhost:8080/deduplicate?data=%5B1%2C23%2C4%2C5%5D
      

      使用邮递员,您想在查询参数窗口中选择您的数据,单击鼠标右键并选择“EncodeURIComponent”:

      Example of encoding using postman 会将您的 URL 转移到

       localhost:8080/deduplicate?data=%5B1%2C23%2C4%2C5%5D
      

      并且它可以被tomcat成功读取(我假设你将它用作servlet容器)。

      如果你不能改变你的前端行为,你可以使用

      relaxedQueryChars/relaxedPathChars

      在连接器定义中允许这些字符。 使用 java 和 spring(如果嵌入了 tomcat):

          @Component
          public class TomcatWebServerSettings implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
              @Override
              public void customize(TomcatServletWebServerFactory factory) {
                  factory.addConnectorCustomizers(connector ->
                  {
                      connector.setAttribute("relaxedQueryChars", "[]");
                  });
              }
          }
      

      或者你可以在server.xml下添加relaxedQueryChars属性(%TOMCAT_FOLDER%/conf/):

        <Connector 
              //other params,
                relaxedQueryChars="[,]"
               />
      

      此外,您可以将您的 tomcat 降级到 7.0.76 以下的版本(强烈不推荐 - 出于安全原因)。

      【讨论】:

        猜你喜欢
        • 2020-10-26
        • 1970-01-01
        • 1970-01-01
        • 2017-10-18
        • 2019-05-10
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 2012-07-22
        相关资源
        最近更新 更多