【问题标题】:PathVariable in Spring ControllerSpring Controller 中的 PathVariable
【发布时间】:2012-02-23 01:42:26
【问题描述】:

我正在尝试映射 url /locations/{locationId}/edit.html - 这似乎与此代码一起使用:

@Controller
@RequestMapping( "/locations" )
public class LocationController
{
  @RequestMapping( value = "/{locationId}/edit.html", method = RequestMethod.GET )
  public String showEditForm( Map<String, Object> map, @PathVariable int locationId )
  {
    map.put( "locationId", locationId );
    return "locationform";
  }
}

调用提到的url会导致异常:

java.lang.IllegalArgumentException: Name for argument type [int] not available, and parameter name information not found in class file either.

我是否以错误的方式使用了@PathVariable 注解?

如何正确使用?

【问题讨论】:

    标签: java spring spring-mvc controller path-variables


    【解决方案1】:

    JDK 7 启用参数名自检

    JDK7提供参数名说明,否则必须在Annotation中设置。

    您应该先使用 JDK 说明,然后再明确使用它(如 Johan 和 Moniul 建议的)作为注释的一部分,因为如果您想更改参数键,您只需要编辑变量名而不是任何其他出现在其他行和/或类中的注释规范。让我们称之为单一事实来源。

    【讨论】:

      【解决方案2】:

      您应该将value 参数添加到您的@PathVariable,例如,

       public String showEditForm(
             @PathVariable("locationId") int locationId,
             Map<String, Object> map) {
          // ...
       }
      

      【讨论】:

        【解决方案3】:

        应该是@PathVariable("locationId") int locationId

        【讨论】:

        • 这里有详细说明,当您的代码在没有调试信息的情况下编译时会发生 (docs.spring.io/spring/docs/3.2.x/spring-framework-reference/…):如果 URI 模板变量名称与方法参数名称匹配,您可以省略该详细信息。只要你的代码不是在没有调试信息的情况下编译的,Spring MVC 就会将方法参数名匹配到 URI 模板变量名
        • 请注意,仅使用“Debug As”进行编译不一定会在项目中包含调试信息。检查你的设置,as detailed here,基本上检查所有的调试探测复选框!
        • 只是想补充一下,似乎还有其他原因。我刚刚从 Spring Boot 1 升级到 2,相同的 JDK 版本,这个问题突然出现在一个 AOP 方面也有问题的测试中,所以我想知道这是否相关。
        猜你喜欢
        • 2013-11-17
        • 2012-08-30
        • 2016-05-26
        • 2012-07-06
        • 2014-09-24
        • 2012-06-08
        • 2013-11-17
        • 1970-01-01
        相关资源
        最近更新 更多