@RequestMapping("/accounts")
public class controller {
@GetMapping("/get/{id}")
public final ResponseEntity<?> getHandler(){
}
@PostMapping(value = "/create")
public final ResponseEntity<?> createHandler(){
/*
trying to use some spring library methods to get the url string of
'/accounts/get/{id}' instead of manually hard coding it
*/
}
}
这是模拟代码,现在我在createHandler中,创建完一些东西后,我想返回一个包含URL字符串的 header ,但我不想手动连接这个URL字符串('/accounts/get/{id}'),它是方法getHandler()
的终点,所以我想知道是否有一种方法可以用来实现这一点?我知道 request.getRequestURI()
,但这仅适用于当前上下文中的 URI。
更多说明:如果有一些库或框架实现了路由:
Routes.Accounts.get(1234)
返回帐户的 URL
/api/accounts/1234
最佳答案
我们的想法是,您不需要指定 get
或 create
(动词在 REST 中是一大禁忌)。
想象一下:
@RequestMapping("/accounts")
public class controller {
@GetMapping("/{id}")
public final ResponseEntity<?> getHandler(@PathVariable("id") String id) {
//just to illustrate
return complicatedHandlerCalculation(id).asResponse();
}
@PostMapping
public final ResponseEntity<?> createHandler() {
//return a 204 Response, containing the URI from getHandler, with {id} resolved to the id from your database (or wherever).
}
}
这可以像HTTP-GET:/api/accounts/1
和HTTP-POST:/api/accounts
一样进行访问,后者将返回/api/accounts/2
的URI(可以使用HTTP-GET
获取或使用HTTP-PUT
更新/修改)
要解析此 URI,您可以使用反射并评估相应类/方法上的注释,就像 Jersey 所做的那样。
Spring 的等价物可能是:
// Controller requestMapping
String controllerMapping = this.getClass().getAnnotation(RequestMapping.class).value()[0];
和
//Method requestMapping
String methodMapping = new Object(){}.getClass().getEnclosingMethod().getAnnotation(GetMapping.class).value()[0];
关于java - Spring Restful API,是否有像路由器一样使用方法来获取其他方法的端点或URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001822/