为啥使用 PathVariable 而不是 PathParam?

Posted

技术标签:

【中文标题】为啥使用 PathVariable 而不是 PathParam?【英文标题】:Why Use PathVariable instead of PathParam?为什么使用 PathVariable 而不是 PathParam? 【发布时间】:2019-03-28 21:47:18 【问题描述】:

在将其标记为重复之前,只是想让你们知道我已经查看了此处发布的问题: What is the difference between @PathParam and @PathVariable

问题是,如果 PathParam 和 PathVariable 的用法相同(只有一个来自 JAX-RS API,一个由 Spring 提供),为什么使用一个给我 null 而另一个给我正确价值?

我正在使用 Postman 来调用该服务: http://localhost:8080/topic/2

(我对 SpringBoot 很陌生)

使用路径参数:

import javax.websocket.server.PathParam;
import org.apache.tomcat.util.json.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TopicController 

    @Autowired
    TopicService topicService;

    @RequestMapping(method=RequestMethod.GET,path="/topic/id")
    public Topic getById(@PathParam("id") long id) throws ParseException 
        return topicService.getTopicById(id);  //-- here id comes as null (when id is declared as a wrapper type - Long, else it throws an error)
    

使用路径变量:

@RestController
public class TopicController 

    @Autowired
    TopicService topicService;

    @RequestMapping(method=RequestMethod.GET,path="/topic/id")
    public Topic getById(@PathVariable("id") long id) throws ParseException 
        return topicService.getTopicById(id);  //-- here id comes as 2
    

【问题讨论】:

【参考方案1】:

我认为你项目中的pathparam在javax.ws下......这个不是他们谈论的。它用于websocket,这意味着它不是http注释。 JBoss 实现 pathparam 需要额外的 jars。

【讨论】:

我导入的是:import javax.websocket.server.PathParam;

以上是关于为啥使用 PathVariable 而不是 PathParam?的主要内容,如果未能解决你的问题,请参考以下文章

Springboot@PathVariable注解使用--请求路径占位符

@PathVariable注解

@RequestParam 和 @PathVariable 有啥区别 [重复]

为啥我总是要使用 ||而不是 |和 && 而不是 &?

为啥使用常量而不是枚举?

为啥 Kivy 使用浮点数而不是整数?