JavaWeb評論功能實現(xiàn)步驟以及代碼實例
前言
評論功能是后端要寫常見的功能之一,一般性的網(wǎng)站也都會包含這一功能。像是購物網(wǎng)站、視頻網(wǎng)站下方都會有用戶評論的功能。
一、分析功能
首先要分析功能:1.用戶登錄點擊商品后可查看所有普通用戶的評論。
2.用戶可以添加評論,發(fā)送到評論區(qū)。
3.用戶可以刪除該用戶寫的評論。(不能刪除其他人的評論)
二、實現(xiàn)功能
1.建評論表
外鍵約束:user_id關聯(lián)user表、motorcycle_id關聯(lián)商品表(motorcycle)。

然后創(chuàng)建實體類。
2.Dao層、service層核心代碼實現(xiàn)
查詢評論:
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層直接調(diào)用,不做處理。
clist = cDao.getMotorcycleComment(motorcycleId);
3.servlet層編寫核心代碼
將查詢結(jié)果放到request域里。
List<Comment> clist=commentService.getMotorcycleComment(id);
// for (Comment c:clist
// ) {
// System.out.println(c);
// }
request.getSession().setAttribute("MotorcycleId", id);
request.setAttribute("clist", clist);調(diào)用刪除后重定向到詳情頁。
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核心代碼

三、展示效果圖
效果查看

添加一條后

數(shù)據(jù)庫變化:新增一條信息

點擊刪除:發(fā)現(xiàn)已經(jīng)沒有該評論。

刷新數(shù)據(jù)庫后:

總結(jié)
效果展示完成。實現(xiàn)起來不算難,但要明白其中的外鍵約束關系,明白其中的邏輯。代碼不是很多,大家快練起來~
到此這篇關于JavaWeb評論功能實現(xiàn)步驟以及代碼實例的文章就介紹到這了,更多相關JavaWeb評論功能實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot?Test的webEnvironment源碼解讀
這篇文章主要為大家介紹了SpringBoot?Test的webEnvironment源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
java構(gòu)造函數(shù)示例(構(gòu)造方法)
這篇文章主要介紹了java構(gòu)造函數(shù)示例(構(gòu)造方法),需要的朋友可以參考下2014-03-03
SpringBoot獲取yml和properties配置文件的內(nèi)容
這篇文章主要為大家詳細介紹了SpringBoot獲取yml和properties配置文件的內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
解讀@Scheduled任務調(diào)度/定時任務非分布式
這篇文章主要介紹了解讀@Scheduled任務調(diào)度/定時任務非分布式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08

