据我所知,两者的目的相同。@PathVariable
除了来自 Spring MVC 和@PathParam
来自 JAX-RS的事实。对此有何见解?
7 回答
@PathVariable和@PathParam都用于从URI 模板访问参数
差异:
- 正如您提到
@PathVariable
的来自 spring 并且@PathParam
来自JAX-RS。 @PathParam
只能与 REST 一起@PathVariable
使用,在 Spring 中使用,因此它可以在 MVC 和 REST 中使用。
查询参数:
将 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) {
@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 模板)
有些人也可以在 Spring 中使用@PathParam,但是当发出 URL 请求时,值将为 null 同时如果我们使用 @PathVarriable,那么如果没有传递值,那么应用程序将抛出错误
@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);
}
@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