lem*_*des 8 java rest spring spring-restcontroller
我使用REST-API还是很新的。
我想要这样的东西
POST http://localhost/posts/ <--- PostsController.java
GET http://localhost/posts/{id} <--- PostsController.java
POST http://localhost/posts/{id}/comments <--- CommentsController.java
GET http://localhost/posts/{id}/comments <--- CommentsController.java
GET http://localhost/posts/{id}/comments/{id} <--- CommentsController.java
Run Code Online (Sandbox Code Playgroud)
以下控制器处理/posts和另一个控制器处理程序的位置/comments
PostsController.java
@RestController
@RequestMapping("/posts")
public class PostsController {
// something
}
Run Code Online (Sandbox Code Playgroud)
CommentsController.java
@RestController
@RequestMapping("/comments")
public class CommentsController {
//do something
}
Run Code Online (Sandbox Code Playgroud)
如何在拥有不同控制器的同时维护上述网址?
这是两个带有端点的控制器的框架,但是您仍然可以将所有这些端点都放在一个控制器中,也可以将它们组合在一起,有些人根据方法,路径来区分它们,所以我相信这完全是开发人员的经验,如何设计这个
PostsController.java
@RestController
@RequestMapping("/posts")
public class PostsController {
@PostMapping("/")
public String createPosts() {
return "createPosts";
}
@GetMapping("/{id}")
public String getPosts(@PathVariable(name = "id") String id) {
return "getPosts......" + id;
}
}
Run Code Online (Sandbox Code Playgroud)
CommentsController.java
@RestController
@RequestMapping("/posts/{id}/comments")
public class CommentsController {
@PostMapping
public String createComment(@PathVariable(name = "id") String id) {
return "createComment..." + id;
}
@GetMapping
public String getComment(@PathVariable(name = "id") String id) {
return "getComment..." + id;
}
@GetMapping("/{id1@Path}")
public String getCommentById(@PathVariable(name = "id") String id, @PathVariable(name = "id1") String id1) {
return "getComment..." + id + "...." + id1;
}
}
Run Code Online (Sandbox Code Playgroud)
我将在这里分享我的经验。当我使用 Rest 控制器时,我总是尝试理解什么是“核心”实体 - 我们处理的概念以及查询的标准是什么。通常“核心”实体出现在上下文路径之后。
请注意,这并不真正取决于数据库级别的实际实现。
所以看起来所有的案例实际上都是关于“帖子”实体的,这就是为什么你把它放在第一位(在帖子评论的情况下,你没有选择这样的东西,http://localhost/comments?post=123没关系,它只是意味着该职位是您要服务的“主要”实体。
在这种情况下,我认为所有操作都可以在PostsController.
现在有一个关于 Spring / SpringBoot 中控制器的重要旁注。人们倾向于将业务逻辑放入这些控制器中,我认为这是一个错误。控制器不应该包含任何真正的逻辑,也许是一些光输入转换/验证,但仅此而已。将真正的工作留给“服务”而不是控制器,让控制器成为后端的入口点。现在我为什么要这么说呢?因为控制器,如果以这种方式编写,实际上是很小的类,所以您不会得到一个处理所有内容的“巨型”类,我相信,这可能是分离到不同控制器的一个论据。
好的,那么本例中的注释是什么?这取决于您如何看待它,但正如您在端点列表中所写的那样,它是帖子的属性(属于帖子/始终与帖子相关联的东西),所以它是“搜索标准”:给我一个有评论的帖子,只给我一个没有评论的帖子,给我一个只有今天和昨天的评论的帖子,重点是你总是查询“帖子”,而不是评论。
从纯粹的技术角度来看,@RequestMapping在Spring Boot中放置控制器类时表示只能/post通过该控制器进行查询。您还可以对@GetMapping/@PostMapping注释设置不同的值,仅此而已。如果应该足够灵活地设计休息控制器的级别。
| 归档时间: |
|
| 查看次数: |
306 次 |
| 最近记录: |