@PathParam 和 @PathVariable 有什么区别

What is the difference between @PathParam and @PathVariable

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

@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

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

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

@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){...}

备注

无论我们通过 rest 调用请求什么,即 @PathVariable

无论我们为编写查询而访问什么,即@RequestParam

查询参数:

将 URI 参数值分配给方法参数。在Spring中是@RequestParam.

例如,

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

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

路径参数:

将 URI 占位符值分配给方法参数。在Spring中是@PathVariable.

例如,

http://localhost:8080/books/1234

@GetMapping("/books/{isbn}")
    public Book getBook(@PathVariable("isbn") String isbn) {

@PathVariable and @PathParam both are used for accessing parameters from URI Template

差异:

  • 正如您提到的,@PathVariable 来自 spring,@PathParam 来自 JAX-RS
  • @PathParam 只能与 REST 一起使用,其中 @PathVariable 在 Spring 中使用,因此它适用于 MVC 和 REST。

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

@PathParam:用于注入在@中定义的命名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);
     }