关键是要使用
UriComponentsBuilder。有几种方法可以获取它的实例
UriComponentsBuilder
从预先配置MvcUriComponentsBuilder
UriComponentsBuilder
作为方法的参数注入
UriComponentsBuilder从预先配置
MvcUriComponentsBuilder
通过这种方式,您可以获取
UriComponentsBuilder已配置为生成
URI指向带有预定义参数的某些控制器方法的指针。
下面是例如,从的javadoc为
MvcUriComponentsBuilder:
例如,给定此控制器:
@RequestMapping("/people/{id}/addresses") class AddressController { @RequestMapping("/{country}") public HttpEntity<Void> getAddressesForCountry(@PathVariable String country) { ... } @RequestMapping(value="/", method=RequestMethod.POST) public void addAddress(Address address) { ... } } A UriComponentsBuilder can be created: // Inline style with static import of "MvcUriComponentsBuilder.on" MvcUriComponentsBuilder.fromMethodCall( on(AddressController.class).getAddressesForCountry("US")).buildAndExpand(1);
有时可能更可取的另一种选择是通过名称指定控制器方法:
UriComponents uriComponents = MvcUriComponentsBuilder.fromMethodName( AddressController.class, "getAddressesForCountry", "US").buildAndExpand(1);URI nextUri = uriComponents.toUri();
UriComponentsBuilder作为方法的参数注入
从spring 3.1开始,
Location可以使用
UriComponentBuilder参数制作并将其设置为return
ResponseEntity。
UriComponentBuilder了解上下文并使用相对路径进行 *** 作:
@RequestMapping(method = RequestMethod.POST)public ResponseEntity<?> createCustomer(UriComponentsBuilder b) { UriComponents uriComponents = b.path("/customers/{id}").buildAndExpand(id); HttpHeaders headers = new HttpHeaders(); headers.setLocation(uriComponents.toUri()); return new ResponseEntity<Void>(headers, HttpStatus.CREATED);}
从4.1版开始,您可以使其更短
@RequestMapping(method = RequestMethod.POST)public ResponseEntity<?> createCustomer(UriComponentsBuilder b) { UriComponents uriComponents = b.path("/customers/{id}").buildAndExpand(id); return ResponseEntity.created(uriComponents.toUri()).build();}
感谢Dieter Hubau指出这一点。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)