学习内容:

1.实现页面的渲染(从数据库拿数据去渲染页面,动态的可修改)

2.实现一个简单的登录功能

3.实现对新闻详情的评论

4.评论的时候可以上传照片

5.本次使用的是mysql+mvc+控制层+过滤器+js文件下的配置文件+webapp下的jsp文件+测试类

6.开发工具IDEA


  • domian层防止了用户+新闻类型+新闻详情+评论 对应MySQL中的四张表
  • dao下进行了数据交互
  • service进行了服务控制
  • controller是控制层
  • filter是过滤器

domain下的四个类:

package com.csi.news.domain;import java.io.Serializable;public class UserInfo implements Serializable {private Integer userId ;private String username ;private String password ;private String sex ;public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}
}
package com.csi.news.domain;import java.io.Serializable;public class NewsType implements Serializable {private Integer typeid ;private String  name ;private String  illustrate ;private String  img ;public Integer getTypeid() {return typeid;}public void setTypeid(Integer typeid) {this.typeid = typeid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getIllustrate() {return illustrate;}public void setIllustrate(String illustrate) {this.illustrate = illustrate;}public String getImg() {return img;}public void setImg(String img) {this.img = img;}
}
package com.csi.news.domain;
import java.io.Serializable;import java.util.Date;
import java.util.Set;public class NewsInfo implements Serializable {private Integer newsId;private String title;private Date time;private String source;private String context;private String edit;private NewsType newsType ;private Set<NewsComments> newsComments ;public Set<NewsComments> getNewsComments() {return newsComments;}public void setNewsComments(Set<NewsComments> newsComments) {this.newsComments = newsComments;}public NewsType getNewsType() {return newsType;}public void setNewsType(NewsType newsType) {this.newsType = newsType;}public Integer getNewsId() {return newsId;}public void setNewsId(Integer newsId) {this.newsId = newsId;}public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public Date getTime() {return time;}public void setTime(Date time) {this.time = time;}public String getSource() {return source;}public void setSource(String source) {this.source = source;}public String getContext() {return context;}public void setContext(String context) {this.context = context;}public String getEdit() {return edit;}public void setEdit(String edit) {this.edit = edit;}}

dao层下的接口和类

package com.csi.news.dao.impl;import com.csi.news.dao.UserInfoDao;
import com.csi.news.domain.UserInfo;
import com.csi.news.utils.JDBCUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;public class UserInfoDaoImpl extends JDBCUtils implements UserInfoDao {@Overridepublic UserInfo login(String username, String password) throws SQLException {final String SQL = "SELECT * FROM user WHERE username = ? AND password = ?" ;//2. 创建JDBC连接Connection connection = this.getConnection();//3. 创建PreparedStatement对象PreparedStatement ps = connection.prepareStatement(SQL);//3.1 设置占位符ps.setString(1,username);ps.setString(2,password);//4. 发起查询,返回ResultSetResultSet rs = ps.executeQuery() ;UserInfo userInfo = null ;//5. 判断结果集是否存在数据if(rs.next()) {//6. 如果存在数据,封装对象,返回对象userInfo = new UserInfo() ;userInfo.setUserId(rs.getInt("UserId"));userInfo.setUsername(rs.getString("username"));userInfo.setSex(rs.getString("sex"));}//7. 关闭资源this.release(rs,ps,connection);return userInfo;}@Overridepublic UserInfo findById(int userId) throws SQLException {final String SQL = "select * from user where userId = ?" ;Connection connection = this.getConnection();PreparedStatement ps = connection.prepareStatement(SQL);ps.setInt(1,userId);ResultSet rs = ps.executeQuery();UserInfo userInfo = null ;if (rs.next()){userInfo = new UserInfo() ;userInfo.setUserId(rs.getInt("UserId"));userInfo.setUsername(rs.getString("Username"));userInfo.setSex(rs.getString("Sex"));userInfo.setPassword(rs.getString("Password"));}this.release(rs,ps,connection);return userInfo;}}
package com.csi.news.dao.impl;import com.csi.news.dao.NewsDao;
import com.csi.news.domain.NewsType;
import com.csi.news.utils.JDBCUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;public class NewsDaoImpl extends JDBCUtils implements NewsDao {@Overridepublic List<NewsType> findShow() throws SQLException {final String SQL = "SELECT * from `news_type`";Connection connection = this.getConnection();PreparedStatement ps = connection.prepareStatement(SQL);ResultSet rs = ps.executeQuery();List<NewsType> news = new ArrayList<>();NewsType news1 = null;while (rs.next()) {news1 = new NewsType();news1.setTypeid(rs.getInt("Type_id"));news1.setName(rs.getString("name"));news1.setIllustrate(rs.getString("illustrate"));news1.setImg(rs.getString("img"));news.add(news1);}release(rs, ps, connection);return news;}@Overridepublic NewsType select(int type_id) throws SQLException {final String SQL = "SELECT * from `news_type` WHERE type_id= ?";Connection connection = this.getConnection();PreparedStatement ps = connection.prepareStatement(SQL);ps.setInt(1, type_id);ResultSet rs = ps.executeQuery();NewsType news = null;if (rs.next()) {news = new NewsType();news.setTypeid(rs.getInt("type_id"));news.setName(rs.getString("name"));news.setIllustrate(rs.getString("illustrate"));news.setImg(rs.getString("img"));}release(rs, ps, connection);return news;}
}
package com.csi.news.dao.impl;import com.csi.news.dao.NewsCommentsDao;
import com.csi.news.dao.NewsInfoDao;
import com.csi.news.domain.NewsComments;
import com.csi.news.domain.NewsInfo;import com.csi.news.utils.JDBCUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;public class NewsInfoDaoImpl extends JDBCUtils implements NewsInfoDao {@Overridepublic NewsInfo findById(int newsId) throws SQLException {final String SQL = "select * from detail where newsId = ?";Connection connection = this.getConnection();PreparedStatement ps = connection.prepareStatement(SQL);ps.setInt(1, newsId);ResultSet rs = ps.executeQuery();NewsInfo newsInfo = null;if (rs.next()) {newsInfo = new NewsInfo();newsInfo.setNewsId(newsId);newsInfo.setTitle(rs.getString("title"));newsInfo.setSource(rs.getString("source"));newsInfo.setContext(rs.getString("context"));newsInfo.setEdit(rs.getString("edit"));newsInfo.setTime(rs.getTimestamp("time"));NewsCommentsDao newsCommentsDao = new NewsCommentsDaoImpl() ;/*List集合转Set集合  set的构造函数中有一个 collection 所以可以写 collection以及 子类*/List<NewsComments> newsComments = newsCommentsDao.list(newsId);Set<NewsComments> set = new HashSet<>(newsComments) ;newsInfo.setNewsComments(set);}release(rs, ps, connection);return newsInfo;}@Overridepublic List<NewsInfo> findShow() throws SQLException {final String SQL = "select * from detail";Connection connection = this.getConnection();PreparedStatement ps = connection.prepareStatement(SQL);ResultSet rs = ps.executeQuery();List<NewsInfo> newsDetails = new ArrayList<>();NewsInfo newsDetail = null;while (rs.next()) {newsDetail = new NewsInfo();newsDetail.setNewsId(rs.getInt("newsId"));newsDetail.setTitle(rs.getString("title"));newsDetail.setSource(rs.getString("source"));newsDetail.setContext(rs.getString("context"));newsDetail.setEdit(rs.getString("edit"));newsDetails.add(newsDetail);}release(rs, ps, connection);return newsDetails;}
}
package com.csi.news.dao.impl;import com.csi.news.dao.NewsCommentsDao;
import com.csi.news.dao.UserInfoDao;
import com.csi.news.domain.NewsComments;
import com.csi.news.domain.UserInfo;
import com.csi.news.utils.JDBCUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;public class NewsCommentsDaoImpl extends JDBCUtils implements NewsCommentsDao {@Overridepublic List<NewsComments> list(int newsId) throws SQLException {final String SQL = "select * from news_comments where newsId = ? " ;Connection connection = this.getConnection();PreparedStatement ps = connection.prepareStatement(SQL);ps.setInt(1,newsId);ResultSet rs = ps.executeQuery();List<NewsComments> newsCommentsList = new ArrayList<>() ;while (rs.next()){NewsComments newsComments = new NewsComments() ;newsComments.setCommentsId(rs.getInt("Comments_Id"));newsComments.setComments_context(rs.getString("Comments_context"));newsComments.setComments_date(String.valueOf(rs.getDate("Comments_date")));/*根据查询到的用户id 去查询相应的对象*/UserInfoDao userInfoDao = new UserInfoDaoImpl() ;UserInfo userInfo = userInfoDao.findById(rs.getInt("userId"));//建立评论与用户的映射关系newsComments.setUserInfo(userInfo);newsCommentsList.add(newsComments) ;}this.release(rs,ps,connection);return newsCommentsList;}@Overridepublic int save(NewsComments newsComments) throws SQLException {final String SQL = "INSERT INTO news_comments(comments_context,comments_date,newsId,userId) VALUES(?,now(),?,?)" ;Connection connection = this.getConnection();PreparedStatement ps = connection.prepareStatement(SQL);ps.setString(1,newsComments.getComments_context());ps.setInt(2,newsComments.getNewsId());ps.setInt(3,newsComments.getUserId());int i = ps.executeUpdate();this.release(ps,connection);return i;}
}

service:

package com.csi.news.service.impl;import com.csi.news.dao.UserInfoDao;
import com.csi.news.dao.impl.UserInfoDaoImpl;
import com.csi.news.domain.UserInfo;
import com.csi.news.service.UserInfoService;import java.sql.SQLException;public class UserInfoServiceImpl implements UserInfoService {@Overridepublic UserInfo login(String username, String password) {UserInfoDao userInfoDao = new UserInfoDaoImpl() ;UserInfo login = null;try {login = userInfoDao.login(username, password);} catch (SQLException e) {e.printStackTrace();}return login;}
}
package com.csi.news.service.impl;import com.csi.news.dao.NewsInfoDao;
import com.csi.news.dao.impl.NewsInfoDaoImpl;
import com.csi.news.domain.NewsInfo;
import com.csi.news.service.NewsInfoService;import java.sql.SQLException;
import java.util.List;public class NewsInfoServiceImpl implements NewsInfoService {@Overridepublic NewsInfo findById(int newsId) {NewsInfoDao newsDetailDao = new NewsInfoDaoImpl() ;NewsInfo byId = null ;try {byId = newsDetailDao.findById(newsId);} catch (SQLException e) {e.printStackTrace();}return byId;}@Overridepublic List<NewsInfo> findShow() {NewsInfoDao newsDetailDao = new NewsInfoDaoImpl() ;List<NewsInfo> show = null;try {show = newsDetailDao.findShow();} catch (SQLException e) {e.printStackTrace();}return show;}
}
package com.csi.news.service.impl;import com.csi.news.dao.NewsDao;
import com.csi.news.dao.impl.NewsDaoImpl;import com.csi.news.domain.NewsType;
import com.csi.news.service.NewsService;
import com.csi.news.utils.JDBCUtils;import java.sql.SQLException;
import java.util.List;public class NewServiceImpl extends JDBCUtils implements NewsService {@Overridepublic List<NewsType> findShow() {NewsDao newsDao = new NewsDaoImpl() ;List<NewsType> show = null;try {show = newsDao.findShow();} catch (SQLException e) {e.printStackTrace();}return show;}@Overridepublic NewsType select(int type_id) {NewsDao newsDao = new NewsDaoImpl() ;NewsType select = null;try {select = newsDao.select(type_id);} catch (SQLException e) {e.printStackTrace();}return select;}
}
package com.csi.news.service.impl;import com.csi.news.dao.NewsCommentsDao;
import com.csi.news.dao.impl.NewsCommentsDaoImpl;
import com.csi.news.domain.NewsComments;
import com.csi.news.service.NewsCommentsService;import java.sql.SQLException;
import java.util.List;public class NewsCommentsServiceImpl implements NewsCommentsService {@Overridepublic int save(NewsComments newsComments) {NewsCommentsDao newsCommentsDao = new NewsCommentsDaoImpl() ;int i = 0;try {i = newsCommentsDao.save(newsComments);} catch (SQLException e) {e.printStackTrace();}return i;}@Overridepublic List<NewsComments> list(int newsId) {NewsCommentsDao newsCommentsDao=new NewsCommentsDaoImpl();List<NewsComments> list=null;try {list = newsCommentsDao.list(newsId);} catch (SQLException e) {e.printStackTrace();}return list;}
}

controller层 用户的登录和注销

package com.csi.news.controller.user;import com.csi.news.domain.UserInfo;
import com.csi.news.service.UserInfoService;
import com.csi.news.service.impl.UserInfoServiceImpl;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;public class LoginController extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");String username = req.getParameter("username");String password = req.getParameter("password");UserInfoService userInfoService = new UserInfoServiceImpl();UserInfo userInfo = userInfoService.login(username, password);if (userInfo !=null){HttpSession session = req.getSession();session.setAttribute("userInfo",userInfo);req.getRequestDispatcher("NewsListController").forward(req,resp);//   req.getRequestDispatcher("comment.jsp").forward(req,resp);}else {resp.sendRedirect("/login.jsp");}}
}
package com.csi.news.controller.user;import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;@WebServlet("/InvalidateController")
public class InvalidateController extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession();session.invalidate();resp.sendRedirect("/index.jsp");}
}

新闻

package com.csi.news.controller.news;import com.csi.news.domain.NewsComments;
import com.csi.news.service.NewsCommentsService;
import com.csi.news.service.impl.NewsCommentsServiceImpl;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/SaveCommentsController")
public class SaveCommentsController extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");String uid = req.getParameter("userId");String nid = req.getParameter("newsId") ;String content = req.getParameter("comments_content") ;int newsId = 0 ;int userId = 0 ;if(nid != null) {newsId = Integer.parseInt(nid.trim()) ;}System.out.println(newsId);if(uid != null) {userId = Integer.parseInt(uid.trim()) ;}NewsComments newsComments =new NewsComments() ;newsComments.setComments_context(content);newsComments.setNewsId(newsId);newsComments.setUserId(userId);NewsCommentsService newsCommentsService =new NewsCommentsServiceImpl() ;int i = newsCommentsService.save(newsComments);if (i > 0){resp.sendRedirect("FindNewsInfoByIdController?newsId=" + newsId);}else {resp.sendRedirect("/error.jsp");}}
}
package com.csi.news.controller.news;import com.csi.news.domain.NewsInfo;
import com.csi.news.domain.UserInfo;
import com.csi.news.service.NewsInfoService;
import com.csi.news.service.impl.NewsInfoServiceImpl;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@WebServlet("/FindNewsInfoByIdController")
public class FindNewsInfoByIdController extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/*        UserInfo userInfo = new UserInfo() ;userInfo.setUsername("admin");userInfo.setUserId(1001);req.getSession().setAttribute("userInfo",userInfo);*/String newsId = req.getParameter("newsId");int nid = 0 ;if (newsId !=null){nid = Integer.parseInt(newsId);}NewsInfoService newsDetailService = new NewsInfoServiceImpl() ;NewsInfo newsInfo = newsDetailService.findById(nid);req.setAttribute("newsInfo",newsInfo);req.getRequestDispatcher("/comment.jsp").forward(req,resp);}
}

文件上传

package com.csi.news.controller.news;import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.simple.JSONObject;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;@WebServlet("/UploadPicController")
public class UploadPicController extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//文件保存目录路径String savePath = req.getServletContext().getRealPath("/") + "attached/";//文件保存目录URLString saveUrl  = req.getContextPath() + "/attached/";//定义允许上传的文件扩展名HashMap<String, String> extMap = new HashMap<String, String>();extMap.put("image", "gif,jpg,jpeg,png,bmp");extMap.put("flash", "swf,flv");extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");//最大文件大小long maxSize = 1000000;resp.setContentType("text/html; charset=UTF-8");PrintWriter out = resp.getWriter() ;if(!ServletFileUpload.isMultipartContent(req)){out.println(getError("请选择文件。"));return;}//检查目录File uploadDir = new File(savePath);if(!uploadDir.exists()) {uploadDir.mkdirs() ;}if(!uploadDir.isDirectory()){out.println(getError("上传目录不存在。"));return;}//检查目录写权限if(!uploadDir.canWrite()){out.println(getError("上传目录没有写权限。"));return;}String dirName = req.getParameter("dir");if (dirName == null) {dirName = "image";}if(!extMap.containsKey(dirName)){out.println(getError("目录名不正确。"));return;}//创建文件夹savePath += dirName + "/";saveUrl += dirName + "/";File saveDirFile = new File(savePath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String ymd = sdf.format(new Date());savePath += ymd + "/";saveUrl += ymd + "/";File dirFile = new File(savePath);if (!dirFile.exists()) {dirFile.mkdirs();}FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");List items = null;try {items = upload.parseRequest(req);} catch (FileUploadException e) {e.printStackTrace();}Iterator itr = items.iterator();while(itr.hasNext()) {FileItem item = (FileItem) itr.next();String fileName = item.getName();long fileSize = item.getSize();if (!item.isFormField()) {//检查文件大小if(item.getSize() > maxSize){out.println(getError("上传文件大小超过限制。"));return;}//检查扩展名String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));return;}SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;try{File uploadedFile = new File(savePath, newFileName);item.write(uploadedFile);}catch(Exception e){out.println(getError("上传文件失败。"));return;}JSONObject obj = new JSONObject();obj.put("error", 0);obj.put("url", saveUrl + newFileName);out.println(obj.toJSONString());}}}private String getError(String message) {JSONObject obj = new JSONObject();obj.put("error", 1);obj.put("message", message);return obj.toJSONString();}
}

商品详情评论

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><%String path =request.getContextPath();String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><title>Title</title><base href="<%=basePath%>"/><link rel="stylesheet" href="${pageContext.request.contextPath}/js/kindeditor/themes/default/default.css" /><link rel="stylesheet" href="${pageContext.request.contextPath}/js/kindeditor/plugins/code/prettify.css" /><script charset="utf-8" src="${pageContext.request.contextPath}/js/kindeditor/kindeditor.js"></script><script charset="utf-8" src="${pageContext.request.contextPath}/js/kindeditor/lang/zh_CN.js"></script><script charset="utf-8" src="${pageContext.request.contextPath}/js/kindeditor/plugins/code/prettify.js"></script><script>KindEditor.ready(function(K) {var editor1 = K.create('textarea[name="comments_content"]', {cssPath : '${pageContext.request.contextPath}/js/kindeditor/plugins/code/prettify.css',uploadJson : '${pageContext.request.contextPath}/UploadPicController',fileManagerJson : '${pageContext.request.contextPath}/js/kindeditor/jsp/file_manager_json.jsp',allowFileManager : true,afterCreate : function() {var self = this;K.ctrl(document, 13, function() {self.sync();document.forms['example'].submit();});K.ctrl(self.edit.doc, 13, function() {self.sync();document.forms['example'].submit();});}});prettyPrint();});</script><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"><script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script><!-- 最新的 Bootstrap 核心 JavaScript 文件 --><script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<body><div><div class="container"><div class="row"><div class="col-md-12 col-md-push-3"><h2 style="font-weight:bold;">${byId.title}</h2><p style="color: gray">${byId.time}  来源:${byId.source}</p></div></div><div class="row"><div class="col-md-12 col-md-push-1"><p style="line-height:45px;font-size: 20px;font-family: '宋体';text-indent: 30px;"></p><p class="navbar-right" style="line-height:45px;font-size: 20px;font-family: '宋体';text-indent: 30px;">${byId.context}<br>  [编辑:${byId.edit}]</p></div></div></div>
</div>
<div><form name="example" method="post" action="SaveCommentsController"><input type="hidden" name="userId" value="${userInfo.userId}" /><input type="hidden" name="newsId" value="${byId.newsId}" /><textarea name="comments_content" cols="100" rows="8" style="width:100%;height:200px;visibility:hidden;"></textarea><br /><input type="submit" name="button" value="提交内容" /> (提交快捷键: Ctrl + Enter)</form>
</div>
<%--循环新闻对应的评论信息列表--%>
<c:forEach items="${newsInfo.newsComments}" var="newsComments"><div style="border: 1px solid deepskyblue;width: 60%"><p><span>${newsComments.comments_date}</span><span style="">${newsComments.userInfo.username}</span></p>${newsComments.comments_context}</div>
</c:forEach></body>
</html>

总结:

1.实现页面渲染和登录功能之后会进入商品详情的评论

2.在进行登录的时候会进行过滤器筛选以及相应的配置,配置文件在web.xml中

3过滤器过滤的是控制层的详情渲染

4.进行详情把评论区设置在详情页面 comment.jsp页面进行设置以及响应的JS文件(未上传)

5.然后进行dao层进行数据交互

6.评论的 dao层会 设置一个对应的用户,==>代表每条评论下会有对应的用户

7.新闻详情页面有所有的评论list集合 以及对应的对应的评论放在Set集合中 ,Set集合会进行重选功能

8.LIst怎么转化为Set集合

9

/*
List集合转Set集合  set的构造函数中有一个 collection 所以可以写 collection以及 子类*/
List<NewsComments> newsComments = newsCommentsDao.list(newsId);Set<NewsComments> set = new HashSet<>(newsComments) ;

10.Set中的构造方法中有一个对应的Collection 类 所一可以放collection以及它的子类

11.在做评论区的时候找到对应的id 对象

<form name="example" method="post" action="SaveCommentsController"><input type="hidden" name="userId" value="${userInfo.userId}" /><input type="hidden" name="newsId" value="${byId.newsId}" /><textarea name="comments_content" cols="100" rows="8" style="width:100%;height:200px;visibility:hidden;"></textarea><br /><input type="submit" name="button" value="提交内容" /> (提交快捷键: Ctrl + Enter)
</form>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><%String path =request.getContextPath();String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><title>Title</title><base href="<%=basePath%>"/><link rel="stylesheet" href="${pageContext.request.contextPath}/js/kindeditor/themes/default/default.css" /><link rel="stylesheet" href="${pageContext.request.contextPath}/js/kindeditor/plugins/code/prettify.css" /><script charset="utf-8" src="${pageContext.request.contextPath}/js/kindeditor/kindeditor.js"></script><script charset="utf-8" src="${pageContext.request.contextPath}/js/kindeditor/lang/zh_CN.js"></script><script charset="utf-8" src="${pageContext.request.contextPath}/js/kindeditor/plugins/code/prettify.js"></script><script>KindEditor.ready(function(K) {var editor1 = K.create('textarea[name="comments_content"]', {cssPath : '${pageContext.request.contextPath}/js/kindeditor/plugins/code/prettify.css',uploadJson : '${pageContext.request.contextPath}/UploadPicController',fileManagerJson : '${pageContext.request.contextPath}/js/kindeditor/jsp/file_manager_json.jsp',allowFileManager : true,afterCreate : function() {var self = this;K.ctrl(document, 13, function() {self.sync();document.forms['example'].submit();});K.ctrl(self.edit.doc, 13, function() {self.sync();document.forms['example'].submit();});}});prettyPrint();});</script><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"><script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script><!-- 最新的 Bootstrap 核心 JavaScript 文件 --><script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</head>
<body><div><div class="container"><div class="row"><div class="col-md-12 col-md-push-3"><h2 style="font-weight:bold;">${byId.title}</h2><p style="color: gray">${byId.time}  来源:${byId.source}</p></div></div><div class="row"><div class="col-md-12 col-md-push-1"><p style="line-height:45px;font-size: 20px;font-family: '宋体';text-indent: 30px;"></p><p class="navbar-right" style="line-height:45px;font-size: 20px;font-family: '宋体';text-indent: 30px;">${byId.context}<br>  [编辑:${byId.edit}]</p></div></div></div>
</div>
<div><form name="example" method="post" action="SaveCommentsController"><input type="hidden" name="userId" value="${userInfo.userId}" /><input type="hidden" name="newsId" value="${byId.newsId}" /><textarea name="comments_content" cols="100" rows="8" style="width:100%;height:200px;visibility:hidden;"></textarea><br /><input type="submit" name="button" value="提交内容" /> (提交快捷键: Ctrl + Enter)</form>
</div>
<%--循环新闻对应的评论信息列表--%>
<c:forEach items="${newsInfo.newsComments}" var="newsComments"><div style="border: 1px solid deepskyblue;width: 60%"><p><span>${newsComments.comments_date}</span><span style="">${newsComments.userInfo.username}</span></p>${newsComments.comments_context}</div>
</c:forEach></body>
</html>
    <filter><filter-name>MyAgentFilter</filter-name><filter-class>com.csi.news.filter.MyAgentFilter</filter-class></filter><filter-mapping><filter-name>MyAgentFilter</filter-name><url-pattern>/NewsDetailController</url-pattern></filter-mapping><filter-mapping><filter-name>MyAgentFilter</filter-name><url-pattern>/NewsThreeController</url-pattern></filter-mapping>

实现评论商品详情的评论功能相关推荐

  1. 企业WEB项目实现商品详情页面展示功能

    概述 在开发电商项目时,我们需要实现一个最基本的功能:点击商品的图片,打开商品详情页面.其中,商品页面分为三大部分: a) 商品基本信息 b) 延迟加载商品详情.延迟一秒加载使用ajax c) 商品的 ...

  2. 拼多多商家制作商品详情页的技巧?

    现在拼多多平台有了商品详情页视频功能,所以商家可以发布商品详情页视频了,目前在电商平台上,商品视频要比图片更能吸引到消费者的注意,所以做好商品详情页视频要比做好主图的效果要好很多哦,但很多商家并不熟练 ...

  3. JavaWeb - 仿小米商城(5):商品详情展示

    JavaWeb - 仿小米商城(5):商品详情展示 1 功能描述 接上篇 JavaWeb - 仿小米商城(4):商品列表形式 本篇博客将分析和实现小米商城商品详情内容的查 询和展示.如下所示: 2 功 ...

  4. java 商城 商品查询_Javaweb网上商城项目实战(17)实现商品详情查询

    原理分析 具体实现 下面是商品详情页面product_info.jsp显示的样子,我们最初的模板的静态资源已经写死了, 这里我们需要先对这个页面进行改造,使得到时候主页点击商品能输出对应的商品详情页面 ...

  5. 仿蘑菇街,蜜芽宝贝,京东商品详情界面,与NestedScroll滑动

    上一篇文章中有提到界面中嵌套NestedScrollView与Fragment并用,而NestedScrollView是不建议与ListView,RecyclerView嵌套的,虽然有解决滑动冲突的办 ...

  6. 基于Spring Boot和Vue3的博客平台文章详情与评论功能实现

    在前面的教程中,我们已经实现了基于Spring Boot和Vue3的发布.编辑.删除文章功能以及文章列表与分页功能.本教程将引导您实现博客平台的文章详情与评论功能. 整个实现过程可以分为以下几个步骤: ...

  7. 1688API接口,获取商品详情,按关键词搜索,拍立淘,商品评论商品类目,店铺接口等

    接口所示 item_get获得1688商品详情 item_search按关键字搜索商品 item_search_img按图搜索1688商品(拍 立淘) item_search_shop获得店铺的所有商 ...

  8. 当当网商品详情API接口(当当商品详情接口,当当商品评论接口,当当商品问答接口,当当抢购价接口,关键词搜索当当网商品接口)代码对接教程

    当当网商品详情API接口(当当商品详情接口,当当商品评论接口,当当商品问答接口,当当抢购价接口,当当商品列表接口)代码对接教程如下: 1.公共参数 名称 类型 必须 描述(接口代码教程wx199701 ...

  9. 当当网商品详情API接口(当当商品详情接口,当当商品评论接口,当当商品问答接口,当当抢购价接口,当当商品列表接口)代码对接教程

    当当网商品详情API接口(当当商品详情接口,当当商品评论接口,当当商品问答接口,当当抢购价接口,当当商品列表接口,关键词搜索当当网商品接口)代码对接教程如下 1.公共参数 名称 类型 必须 描述(接口 ...

最新文章

  1. 支付宝的架构到底有多牛逼!还没看完我就跪了!
  2. 排序算法---冒泡排序(java版)
  3. Python - 3.6 学习三
  4. android7.1.2 user版本打开usb调试功能
  5. Ubuntu18.04安装Scala
  6. 13.5.SolrCloud集群使用手册之数据导入
  7. mysql 获取下一条记录数,如何在MySQL中查询当前数据上一条和下一条的记录
  8. 学习网页前的网页知识储备
  9. python自动化测试-Python自动化测试如何自动生成测试用例?
  10. 元素的水平垂直居中解决方法
  11. BC 2015在百度之星程序设计大赛 - 预赛(1)(KPI-树董事长)
  12. paip.信用卡账单处理系统功能vO22
  13. Jave_erhui
  14. 笔记本电脑开机键盘失效
  15. 如何在Firefox中播放MID文件?
  16. 数字阵列麦克风处理技术概述
  17. 清华大学计算机杜瑜皓,我在清华等你来|2015国际信息学奥赛全球第四名杜瑜皓:人生不搏枉少年...
  18. 昂达V971四核测评
  19. Multisim电路分析仿真-叠加原理
  20. 电商系统的商品库存管理

热门文章

  1. wordpress主题推荐
  2. stata软件不出图_stata软件做出的森林图像素不够咋办
  3. numpy 矩阵对角线_NumPy 构建规则矩阵
  4. 手把手带你制作WIFI智能开关.走进物联网-ESP8266学习日记(一)
  5. 开学季学生党必备的蓝牙耳机有哪些?超实用的平价蓝牙耳机推荐
  6. 计算机英语中级职称题库,中级职称计算机试题练习.doc
  7. 络达开发-MCU中添加用户自定义功能模块
  8. 【学习整理】天基移动通信网络
  9. Python安装下载 ,装Python只需这么几步
  10. DALI Cookbook by Eric