Spring控制器中的PathVariable

25
我试图映射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注解?

如何正确使用它?

3个回答

40

应该使用@PathVariable("locationId") int locationId


9
这里有详细的说明,当您的代码没有调试信息进行编译时会出现这种情况(http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html):如果URI模板变量名与方法参数名匹配,则可以省略该细节。只要您的代码不是没有调试信息编译的,Spring MVC就会将方法参数名与URI模板变量名进行匹配。 - TheWestIsThe...
请注意,仅使用“Debug As”编译项目不一定会包含调试信息。请检查您的设置,如此处所述,并基本上勾选所有调试相关的复选框! - TheWestIsThe...
只想补充一下,似乎还有其他原因。我刚从Spring Boot 1升级到2,JDK版本相同,这个问题突然出现在一个测试中,该测试也遇到了AOP方面的问题,所以我想知道是否相关。 - Sander Verhagen

16

你应该在你的 @PathVariable 中添加 value 参数,例如:

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

0

JDK 7 可以实现参数名称内省

在 JDK7 中,可以使用参数名称内省功能,否则必须在注释中设置。

在显式使用注释之前,应该先使用 JDK 内省,因为如果您想要更改参数键,您只需要编辑变量名称,而不是其他行和/或类中的注释规范中的任何其他出现。让我们称其为单一真相来源。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接