



本节需要创建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将处理有关电影评论的请求。以下是一个基础的实现代码。
@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);
}
}