What is the difference between @PathParam and @PathVariable

有些话、适合烂在心里 提交于 2019-12-03 18:45:46

问题


To my knowledge both serves the same purpose. Except the fact that @PathVariable is from Spring MVC and @PathParam is from JAX-RS. Any insights on this?


回答1:


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

Differences:

  • As you mention @PathVariable is from spring and @PathParam is from JAX-RS.
  • @PathParam can use with REST only, where @PathVariable used in Spring so it works in MVC and REST.



回答2:


PathParam:

To assign URI parameter values to method arguments. In Spring, it is @RequestParam.

Eg.,

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

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

PathVariable:

To assign URI placeholder values to method arguments.

Eg.,

http://localhost:8080/books/1234

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



回答3:


@PathParam is a parameter annotation which allows you to map variable URI path fragments into your method call.

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

for more details : JBoss DOCS

In Spring MVC you can use the @PathVariable annotation on a method argument to bind it to the value of a URI template variable for more details : SPRING DOCS




回答4:


@PathParam is a parameter annotation which allows you to map variable URI path fragments into your method call.

@PathVariable is to obtain some placeholder from the URI (Spring call it an URI Template)




回答5:


@PathVariable

@PathVariable it is the annotation, that is used in the URI for the incoming request. Let’s look below

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

@RequestParam

@RequestParam annotation used for accessing the query parameter values from the request.

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

Note

whatever we are requesting with rest call i.e, @PathVariable

whatever we are accessing for writing queries i.e, @RequestParam



来源:https://stackoverflow.com/questions/32367501/what-is-the-difference-between-pathparam-and-pathvariable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!