为什么使用PathVariable而不是PathParam?

问题描述 投票:0回答:1

在将此标记为重复之前,只是希望你们知道我已经检查了这里发布的问题:What is the difference between @PathParam and @PathVariable

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

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

(我对Spring Boot很新)

使用PathParam:

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)
    }
}

使用PathVariable:

@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个回答
0
投票

我认为你项目中的路径参数是在javax.ws下...这个不是他们所说的。它用于websocket,这意味着它不是一个http注释。 JBoss实现pathparam需要额外的jar。

© www.soinside.com 2019 - 2024. All rights reserved.