【问题标题】:Spring REST API not mapping path variables correctlySpring REST API 未正确映射路径变量
【发布时间】:2017-06-07 07:17:06
【问题描述】:

我有以下请求映射:

@RequestMapping(value = {"/product/{id}-{name}"}, method = RequestMethod.GET)

当我使用“/product/1-product-name-here”对此端点执行 GET 时,我收到以下错误:

无法将“java.lang.String”类型的值转换为所需的“int”类型;嵌套异常是 java.lang.NumberFormatException

谁能建议我应该怎么做才能解决这个问题?我假设 Spring 会将第一个破折号之前的任何内容作为 ID,并将其后的任何内容作为名称,但事实并非如此。

如果我使用 /product/1-name 执行 GET,它可以正常工作。如果路径变量包含破折号,这似乎是一些奇怪的行为。

谢谢

【问题讨论】:

  • 您的- 分隔符有问题。只需将 url 更改为:"/product/{id}/{name}" 就可以了。

标签: java spring spring-mvc


【解决方案1】:

尝试以下方法:

@RequestMapping(value = {"/product/{id:\\d+}-{name}"}, method = RequestMethod.GET)

您可以为路径变量提供正则表达式。您需要在冒号(:) 之后给出正则表达式。

参考:https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates-regex

【讨论】:

    【解决方案2】:

    添加绑定注解@PathVariable并将其分配给所需的变量类型

    @RequestMapping(value = "/product/{id}/{name}", method = RequestMethod.GET)
    public void yourMethod(@PathVariable("id") Long id,  @PathVariable("name") String  name )
    {
     ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-05
      • 2015-01-18
      • 2015-01-25
      • 2022-10-13
      • 2014-01-24
      • 2013-03-30
      • 1970-01-01
      • 2020-09-26
      相关资源
      最近更新 更多