60

据我所知,两者的目的相同。@PathVariable除了来自 Spring MVC 和@PathParam来自 JAX-RS的事实。对此有何见解?

4

7 回答 7

63

@PathVariable@PathParam都用于从URI 模板访问参数

差异:

  • 正如您提到@PathVariable的来自 spring 并且@PathParam来自JAX-RS
  • @PathParam只能与 REST 一起@PathVariable使用,在 Spring 中使用,因此它可以在 MVC 和 REST 中使用。
于 2018-03-25T02:54:15.493 回答
38

查询参数:

将 URI 参数值分配给方法参数。在春天,它是@RequestParam

例如。,

http://localhost:8080/books?isbn=1234

@GetMapping("/books/")
    public Book getBookDetails(@RequestParam("isbn") String isbn) {

路径参数:

将 URI 占位符值分配给方法参数。在春天,它是@PathVariable

例如。,

http://localhost:8080/books/1234

@GetMapping("/books/{isbn}")
    public Book getBook(@PathVariable("isbn") String isbn) {
于 2018-01-28T07:21:34.600 回答
11

@PathParam是一个参数注释,它允许您将变量 URI 路径片段映射到您的方法调用中。

@Path("/library")
public class Library {

   @GET
   @Path("/book/{isbn}")
   public String getBook(@PathParam("isbn") String id) {
      // search my database and get a string representation and return it
   }
}

更多细节:JBoss DOCS

在 Spring MVC 中,您可以在方法参数上使用@PathVariable注释将其绑定到 URI 模板变量的值以获取更多详细信息:SPRING DOCS

于 2016-09-20T12:56:48.510 回答
1

@PathParam是一个参数注释,它允许您将变量 URI 路径片段映射到您的方法调用中。

@PathVariable是从 URI 中获取一些占位符(Spring 将其称为 URI 模板)

于 2016-09-21T09:15:36.457 回答
0

有些人也可以在 Spring 中使用@PathParam,但是当发出 URL 请求时,值将为 null 同时如果我们使用 @PathVarriable,那么如果没有传递值,那么应用程序将抛出错误

于 2020-05-12T13:01:50.990 回答
-1

@PathParam:它用于注入在@Path表达式中定义的命名 URI 路径参数的值。

前任:

@GET
@Path("/{make}/{model}/{year}")
@Produces("image/jpeg")
public Jpeg getPicture(@PathParam("make") String make, @PathParam("model") PathSegment car, @PathParam("year") String year) {
        String carColor = car.getMatrixParameters().getFirst("color");

}

@Pathvariable:该注解用于处理请求URI映射中的模板变量,并将它们用作方法参数。

前任:

     @GetMapping("/{id}")
     public ResponseEntity<Patient> getByIdPatient(@PathVariable Integer id) {
          Patient obj =  service.getById(id);
          return new ResponseEntity<Patient>(obj,HttpStatus.OK);
     }
于 2020-12-21T15:16:38.287 回答
-2

@PathVariable

@PathVariable 它是注解,在 URI 中用于传入请求。

http://localhost:8080/restcalls/101?id=10&name=xyz

@RequestParam

@RequestParam 注解用于访问请求中的查询参数值。

public String getRestCalls(
@RequestParam(value="id", required=true) int id,
@RequestParam(value="name", required=true) String name){...}

笔记

无论我们在休息时要求什么,即@PathVariable

我们为编写查询而访问的任何内容,即@RequestParam

于 2017-09-18T16:29:32.683 回答