购买
下载掌阅APP,畅读海量书库
立即打开
畅读海量书库
扫码下载掌阅APP

2.6.3 创建RESTful控制器

本节需要创建RESTful控制器来处理客户端的请求。在这一步,将实现两个主要的控制器:MovieController和CommentController。这两个控制器将负责处理与电影列表、详情、评论和评分相关的请求。

MovieController将处理有关电影的请求。以下是基础的实现代码。

    @RestController
    @RequestMapping("/api/movies")
    public class MovieController {
 
        // 获取所有电影
        @GetMapping
        public ResponseEntity<List<Movie>> getAllMovies() {
            List<Movie> movies = Movie.getAllMovies();
            return ResponseEntity.ok(movies);
        }
        // 根据ID获取电影
        @GetMapping("/{id}")
        public ResponseEntity<Movie> getMovieById(@PathVariable Long id) {
            Movie movie = Movie.getMovieById(id);
            if (movie != null) {
                return ResponseEntity.ok(movie);
            } else {
                return ResponseEntity.notFound().build();
            }
        }
        // 添加电影
        @PostMapping
        public ResponseEntity<Movie> addMovie(@RequestBody Movie movie) {
            Movie.addMovie(movie);
            return ResponseEntity.ok(movie);
        }
        // 根据ID删除电影
        @DeleteMapping("/{id}")
        public ResponseEntity<Void> deleteMovie(@PathVariable Long id) {
            Movie movie = Movie.getMovieById(id);
            if (movie != null) {
                Movie.deleteMovie(id);
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.notFound().build();
          }
       }
    }

CommentController将处理有关电影评论的请求。以下是一个基础的实现代码。 zSGW9/Jn5NjS1OFf7WcGoXx2I73aqEtvXCsCya6/rt82JInQ+JG+MGXcC6kKUmFr

    @RestController
    @RequestMapping("/api/comments")
    public class CommentController {
 
        // 根据电影ID获取评论
        @GetMapping("/{movieId}")
        public ResponseEntity<List<Comment>> getCommentsByMovieId(@PathVariable
    Long movieId) {
            List<Comment> comments = Comment.getCommentsByMovieId(movieId);
            if (!comments.isEmpty()) {
                return ResponseEntity.ok(comments);
            } else {
                return ResponseEntity.notFound().build();
            }
        }
        // 添加评论
        @PostMapping
        public ResponseEntity<Comment> addComment(@RequestBody Comment comment) {
            Comment.addComment(comment);
            return ResponseEntity.ok(comment);
        }
    }
点击中间区域
呼出菜单
上一章
目录
下一章
×