我希望这不是一个太简单的问题。我是 Java Web 服务领域的新手,似乎无法访问我的 Controller 中的 PathVariables。我正在使用 STS,它不会提示我的语法错误。
比正确答案更重要的是,我真的很想知道为什么这行不通。
这是一些我无法开始工作的示例代码:
@RestController
public class TestController {
@RequestMapping("/example")
public String doAThing(
@PathVariable String test
) throws MessagingException {
return "Your variable is " + test;
}
}
如果我像这样对它运行 curl :
curl http://localhost:8080/example?test=foo
我收到以下回复:
{"timestamp":1452414817725,"status":500,"error":"Internal Server Error","exception":"org.springframework.web.bind.MissingPathVariableException","message":"Missing URI template variable 'test' for method parameter of type String","path":"/example"}
我知道我已正确连接所有其他设备,其他 Controller 正常工作。
我觉得我一定错过了一些基本原则。
提前致谢。
最佳答案
Spring 支持不同的方式将内容从 url 映射到方法参数:请求参数和路径变量
请求参数取自 url 查询参数(和请求正文,例如在 http-POST 请求中)。标记应从请求参数中获取其值的 java 方法参数的注释是
@RequestParam
路径变量(有时称为路径模板)是 url 路径的一部分。标记应从请求参数中获取其值的 java 方法参数的注释是
@PathVariable
看看this answer我的,例如 Spring Reference 的链接。
那么你的问题是什么:你想读取一个请求参数(从 url-query 部分),但是使用了路径变量的注释。所以你必须使用 @RequestParam
而不是 @PathVariable
:
@RestController
public class TestController {
@RequestMapping("/example")
public String doAThing(@RequestParam("test") String test) throws MessagingException {
return "Your variable is " + test;
}
}
关于java - 如何使用 spring 正确管理 PathVariables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34703568/