添加了getById的请求方法

This commit is contained in:
高子兴 2024-07-04 00:33:32 +08:00
parent 9056250574
commit 431ef62c12
2 changed files with 17 additions and 1 deletions

View File

@ -24,6 +24,15 @@ public class NewsController {
return new ResponseEntity<>(newsService.getNewsByPage(pageNo, pageSize), HttpStatus.OK); return new ResponseEntity<>(newsService.getNewsByPage(pageNo, pageSize), HttpStatus.OK);
} }
@GetMapping("/{id}")
public ResponseEntity<News> getNewsPage(@PathVariable Long id) {
try {
return new ResponseEntity<>(newsService.getNewsById(id), HttpStatus.OK);
} catch (EntityNotFoundException e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@PostMapping @PostMapping
@JwtVerify @JwtVerify
public ResponseEntity<MessageResponse> createNews(@RequestBody NewsRequest request) { public ResponseEntity<MessageResponse> createNews(@RequestBody NewsRequest request) {
@ -34,7 +43,7 @@ public class NewsController {
} catch (Exception e) { } catch (Exception e) {
return new ResponseEntity<>(new MessageResponse("创建失败:" + e.getMessage()), HttpStatus.BAD_REQUEST); return new ResponseEntity<>(new MessageResponse("创建失败:" + e.getMessage()), HttpStatus.BAD_REQUEST);
} }
return new ResponseEntity<>(new MessageResponse("创建成功"), HttpStatus.OK); return new ResponseEntity<>(new MessageResponse("创建成功"), HttpStatus.CREATED);
} }
@PutMapping("/{id}") @PutMapping("/{id}")

View File

@ -54,4 +54,11 @@ public class NewsService {
} }
newsRepository.deleteById(id); newsRepository.deleteById(id);
} }
public News getNewsById(Long id) {
if (!newsRepository.existsById(id)) {
throw new EntityNotFoundException();
}
return newsRepository.findById(id).orElse(null);
}
} }