上QQ阅读APP看书,第一时间看更新
Implementation of Controllers annotations
The following is CommentController, which displays and saves comment:
@Controller
public class CommentController {
private final static Logger LOGGER = LoggerFactory.getLogger(CommentController.class);
private final CommentService commentService;
public CommentController(CommentService commentService) {
this.commentService = commentService;
}
@GetMapping("/")
public String index(Model model) {
model.addAttribute("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
List<Comment> allComments = commentService.getAllCommentsForToday();
Map<CommentType, List<Comment>> groupedComments =
allComments.stream().collect(Collectors.groupingBy(Comment::getType));
model.addAttribute("starComments", groupedComments.get(CommentType.STAR));
model.addAttribute("deltaComments", groupedComments.get(CommentType.DELTA));
model.addAttribute("plusComments", groupedComments.get(CommentType.PLUS));
return "comment";
}
@PostMapping("/comment")
public String createComment(@RequestParam(name = "plusComment", required = false) String plusComment,
@RequestParam(name = "deltaComment", required = false) String deltaComment,
@RequestParam(name = "starComment", required = false) String starComment) {
List<Comment> comments = new ArrayList<>();
if (StringUtils.isNotEmpty(plusComment)) {
comments.add(getComment(plusComment, CommentType.PLUS));
}
if (StringUtils.isNotEmpty(deltaComment)) {
comments.add(getComment(deltaComment, CommentType.DELTA));
}
if (StringUtils.isNotEmpty(starComment)) {
comments.add(getComment(starComment, CommentType.STAR));
}
if (!comments.isEmpty()) {
LOGGER.info("Saved {}", commentService.saveAll(comments));
}
return "redirect:/";
}
private Comment getComment(String comment, CommentType commentType) {
Comment commentObject = new Comment();
commentObject.setType(commentType);
commentObject.setComment(comment);
return commentObject;
}
}
The index method, which is mapped to the URL /, will load comments made on the day using CommentService.getAllCommentsForToday(). After that, it will group all comments by comment type and send those to be displayed on the comment page.
The createComment method, which is mapped to the URL /comment, will save comments made on the day using the CommentService.saveAll() method.