【问题标题】: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
    }
}

【问题讨论】:

    标签: rest spring-boot


    【解决方案1】:

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

    【讨论】:

    • 我导入的是:import javax.websocket.server.PathParam;
    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2021-10-12
    • 2011-10-14
    相关资源
    最近更新 更多