评论功能是后端要写常见的功能之一,一般性的网站也都会包含这一功能。像是购物网站、视频网站下方都会有用户评论的功能。
首先要分析功能:1.用户登录点击商品后可查看所有普通用户的评论。
2.用户可以添加评论,发送到评论区。
3.用户可以删除该用户写的评论。(不能删除其他人的评论)
外键约束:user_id关联user表、motorcycle_id关联商品表(motorcycle)。

然后创建实体类。
查询评论:
String sql="select c.id, c.user_id,c.motorcycle_id,c.motorcycle_comment,u.username from comment c left join user u on c.user_id=u.id where c.motorcycle_id=?";
添加评论:
String sql = "insert into comment(user_id,motorcycle_id,motorcycle_comment) values(?,?,?)"
删除评论:
String sql = "delete from comment where id=?";
service层直接调用,不做处理。
clist = cDao.getMotorcycleComment(motorcycleId);
将查询结果放到request域里。
- List
clist=commentService.getMotorcycleComment(id); - // for (Comment c:clist
- // ) {
- // System.out.println(c);
- // }
- request.getSession().setAttribute("MotorcycleId", id);
- request.setAttribute("clist", clist);
调用删除后重定向到详情页。
- commentService.deleteComment(commentId);
- resp.sendRedirect("/motorcycle_detail?id="+motorcycleId);
添加也是,添加完后重定向到商品详情页。
- CommentService commentService=new CommentService();
- int userId= Integer.parseInt(req.getParameter("userId"));
- int motorcycleId= Integer.parseInt(req.getParameter("motorcycleId"));
- String motorcycleComment=req.getParameter("comment");
-
- commentService.addComment(userId,motorcycleId,motorcycleComment);
- // req.getRequestDispatcher("/motorcycle_detail?id="+motorcycleId).forward(req, resp);
- resp.sendRedirect("/motorcycle_detail?id="+motorcycleId);

效果查看

添加一条后

数据库变化:新增一条信息

点击删除:发现已经没有该评论。

刷新数据库后:

效果展示完成。实现起来不算难,但要明白其中的外键约束关系,明白其中的逻辑。代码不是很多,大家快练起来~