JavaWeb評論功能實現(xiàn)步驟以及代碼實例
前言
評論功能是后端要寫常見的功能之一,一般性的網(wǎng)站也都會包含這一功能。像是購物網(wǎng)站、視頻網(wǎng)站下方都會有用戶評論的功能。
一、分析功能
首先要分析功能:1.用戶登錄點擊商品后可查看所有普通用戶的評論。
2.用戶可以添加評論,發(fā)送到評論區(qū)。
3.用戶可以刪除該用戶寫的評論。(不能刪除其他人的評論)
二、實現(xiàn)功能
1.建評論表
外鍵約束:user_id關(guān)聯(lián)user表、motorcycle_id關(guān)聯(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)起來不算難,但要明白其中的外鍵約束關(guān)系,明白其中的邏輯。代碼不是很多,大家快練起來~
到此這篇關(guān)于JavaWeb評論功能實現(xiàn)步驟以及代碼實例的文章就介紹到這了,更多相關(guān)JavaWeb評論功能實現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot使用@Async注解可能會遇到的8大坑點匯總
SpringBoot中,@Async注解可以實現(xiàn)異步線程調(diào)用,用法簡單,體驗舒適,但是你一定碰到過異步調(diào)用不生效的情況,今天,我就列出90%的人都可能會遇到的8大坑點,需要的朋友可以參考下2023-09-09
springboot2.0?@Slf4j?log?彩色日志配置輸出到文件
這篇文章主要介紹了springboot2.0 @Slf4j log日志配置輸出到文件(彩色日志),解決方式是使用了springboot原生自帶的一個log框架,結(jié)合實例代碼給大家講解的非常詳細,需要的朋友可以參考下2023-08-08
spring cloud gateway如何獲取請求的真實地址
這篇文章主要介紹了spring cloud gateway如何獲取請求的真實地址問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
SpringMvc向request域中設(shè)置數(shù)據(jù)的方法
這篇文章主要介紹了SpringMvc向request域中設(shè)置數(shù)據(jù)的方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
Spring Boot與Kotlin定時任務(wù)的示例(Scheduling Tasks)
這篇文章主要介紹了Spring Boot與Kotlin定時任務(wù)的示例(Scheduling Tasks),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03

