JavaWeb评论功能实现步骤及代码

文章目录


前言

评论功能是后端要写常见的功能之一,一般性的网站也都会包含这一功能。像是购物网站、视频网站下方都会有用户评论的功能。

 

一、分析功能

首先要分析功能:1.用户登录点击商品后可查看所有普通用户的评论。

                             2.用户可以添加评论,发送到评论区。

                             3.用户可以删除该用户写的评论。(不能删除其他人的评论)

二、实现功能

1.建评论表

外键约束:user_id关联user表、motorcycle_id关联商品表(motorcycle)。

 然后创建实体类。

2.Dao层、service层核心代码实现

查询评论:

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);

 3.servlet层编写核心代码

将查询结果放到request域里。

List<Comment> 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);

 4.jsp核心代码

 


 三、展示效果图

效果查看

添加一条后

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

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

 刷新数据库后:

 

总结

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

  • 24
    点赞
  • 175
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 32
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 32
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心态还需努力呀

你的鼓励将是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值