如何使用Spring正确管理PathVariables

Bry*_*yan 1 java spring

我希望这不是一个简单的问题。我是Java Web服务世界的新手,似乎无法在控制器中访问PathVariables。我正在使用STS,并且没有抱怨我的语法错误。

比正确答案重要得多,我真的很想知道为什么这不起作用。

这是一些我无法使用的示例代码:

@RestController
public class TestController {

    @RequestMapping("/example")
    public String doAThing(
        @PathVariable String test
    ) throws MessagingException {
        return "Your variable is " + test;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我像这样卷曲一下:

curl http://localhost:8080/example?test=foo
Run Code Online (Sandbox Code Playgroud)

我收到以下答复:

{“时间戳”:1452414817725,“状态”:500,“错误”:“内部服务器错误”,“例外”:“ org.springframework.web.bind.MissingPathVariableException”,“消息”:“缺少URI模板变量'test '用于类型为String“,” path“:” / example“}的方法参数

我知道我已正确连接了其他所有设备,其他控制器也正常工作。

我觉得我这里一定缺少一些基本原理。

提前致谢。

pre*_*mar 5

如果使用路径变量,则它必须是URI的一部分。正如您没有在URI中提到的那样,而是在方法参数中使用的,spring尝试从路径URI中找出并分配该值。但是此路径变量不在路径URI中,因此抛出MissingPathVariableException。

这应该工作。

@RestController
public class TestController {

@RequestMapping("/example/{test}")
public String doAThing(
    @PathVariable String test
) throws MessagingException {
    return "Your variable is " + test;
}
}
Run Code Online (Sandbox Code Playgroud)

而你的卷曲要求就像

curl http://localhost:8080/example/foo
//here the foo can be replace with other string values
Run Code Online (Sandbox Code Playgroud)


Ral*_*lph 5

Spring 支持如何将内容从 url 映射到方法参数的不同方式:请求参数和路径变量

  • 请求参数取自 url-query 参数(和请求正文,例如在 http-POST 请求中)。标记应该从请求参数中获取其值的 java 方法参数的注释是@RequestParam

  • 路径变量(有时称为路径模板)是 url-path 的一部分。标记应该从请求参数中获取其值的 java 方法参数的注释是@PathVariable

看看我的这个答案,例如一个指向 Spring 参考的链接。

那么您的问题是:您想读取请求参数(来自 url-query 部分),但使用了路径变量的注释。所以你必须使用@RequestParam而不是@PathVariable

@RestController
public class TestController {

    @RequestMapping("/example")
    public String doAThing(@RequestParam("test") String test) throws MessagingException {
        return "Your variable is " + test;
    }
}
Run Code Online (Sandbox Code Playgroud)