如何使用 spring 正确管理 PathVariables
Posted
技术标签:
【中文标题】如何使用 spring 正确管理 PathVariables【英文标题】:How to properly manage PathVariables with spring 【发布时间】:2016-04-14 16:50:05 【问题描述】:我希望这不是一个太简单的问题。我是 Java Web 服务世界的新手,似乎无法访问我的控制器中的 PathVariables。我正在使用 STS,它并没有抱怨我的语法错误。
比正确答案更重要,我真的很想知道为什么这不起作用。
这是一些我无法工作的示例代码:
@RestController
public class TestController
@RequestMapping("/example")
public String doAThing(
@PathVariable String test
) throws MessagingException
return "Your variable is " + test;
如果我像这样对它进行卷曲:
curl http://localhost:8080/example?test=foo
我收到以下回复:
"timestamp":1452414817725,"status":500,"error":"内部服务器 错误","异常":"org.springframework.web.bind.MissingPathVariableException","消息":"丢失 用于方法参数类型的 URI 模板变量“测试” 字符串","路径":"/example"
我知道我已经正确连接了所有其他东西,其他控制器也可以正常工作。
我觉得我必须在这里遗漏一些基本原则。
提前致谢。
【问题讨论】:
是:您在请求中使用的是查询参数 (@RequestParam
) 而不是路径变量。
对我来说,当我错误地使用 @PathVariable
而不是 @RequestParam
时发生 MissingPathVariableException
【参考方案1】:
Spring 支持将 url 中的内容映射到方法参数的不同方式:请求参数和路径变量
请求参数取自 url-query 参数(和请求正文,例如在 http-POST 请求中)。标记应该从请求参数中获取其值的 java 方法参数的注释是 @RequestParam
路径变量(有时称为路径模板)是 url 路径的一部分。标记应从请求参数中获取其值的 java 方法参数的注释是 @PathVariable
看看我的this answer,例如一个指向 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;
【讨论】:
当然,我什至没有正确地问这个问题。非常感谢。【参考方案2】:如果您使用路径变量,那么它必须是 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;
你的 curl 请求会是这样的
curl http://localhost:8080/example/foo
//here the foo can be replace with other string values
【讨论】:
【参考方案3】:它不起作用的原因是有两种方法可以使用 RestController 将参数传递给 REST API 实现。一个是 PathVariable,另一个是 RequestParam。两者都需要在 RequestMapping 注解中指定名称。
查看 this 详细解释 RequestMapping 的优秀资源
试试这个作为你的解决方案。
@RequestMapping("/example/test", method= RequestMethod.GET)
public String doAThing(
@PathVariable("test") String test
) throws MessagingException
return "Your variable is " + test;
【讨论】:
【参考方案4】:我的解决方案是:
@RestController
@RequestMapping("/products")
@EnableTransactionManagement
public class ProductController
@RequestMapping(method = RequestMethod.POST)
public Product save(@RequestBody Product product)
Product result = productService.save(product);
return result;
【讨论】:
以上是关于如何使用 spring 正确管理 PathVariables的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot数据如何使Query正确管理NumberLong?
在 Spring Cloud Stream Kafka 中正确管理 DLQ