一、注册功能
1、约定前后端接口
2、后端代码编写
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//设置编码,告诉 Servlet 按照什么格式来理解请求req.setCharacterEncoding("utf8");//设置响应的编码,告诉 Servlet 按照什么格式来构造请求resp.setContentType("text/html;charset=utf8");//1、读取参数中的用户名和密码String username = req.getParameter("username");String password = req.getParameter("password");if (username == null || "".equals(username) || password == null || "".equals(password)){//注册失败String html = "<h3>注册失败!缺少 username 或者 password 字段!</h3>";resp.getWriter().write(html);return;}//2、读数据库,看看数据库中是否存在 usernameUserDao userDao = new UserDao();User user = userDao.selectByUsername(username);if (user != null){//用户已经存在String html = "<h3>注册失败!该用户已经存在,请重新注册用户!";resp.getWriter().write(html);return;}//用户不存在,注册用户userDao.add(username,password);//注册完自动跳转到登录页面resp.sendRedirect("login.html");}
}
3、前端代码编写
为了添加一个注册的功能,我重新编写了一个专门用于注册的页面,该页面与登录页面类似
并且在登录页面中新添加了一个注册的按钮,当用户点击到注册按钮之后,就会自动跳转到注册页面进行注册
4、遇到的问题
当设计好注册功能后,我新注册了一个账户,并登录该账户,发现该账户虽然并没有发布任何的博客,但是仍然可以查询到别的用户发布的博客内容,于是我对 BlogDao 中的方法和 博客列表页的 doGet 进行了一些修改
在 selectAll 方法中,不再是查询全部的博客信息,而是只查询对应 userId 的博客,也就是登录的用户自己发布的博客内容而查询的所需要的 userId 的信息,则是从 session 中获取,这样就可以将两个账户发表的博客进行一个有效的分开
二、修改已发布文章功能
1、约定前后端接口
点击编辑按钮跳转到编辑页面时,使用 GET
编辑文章后提交新的文章,使用 POST
2、后端代码编写
@WebServlet("/update")
public class updateServlet extends HttpServlet {private ObjectMapper objectMapper = new ObjectMapper();private int BlogId = 0;protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1. 检查当前用户是否登录resp.setContentType("application/json;charset=utf-8");HttpSession session = req.getSession(false);if (session == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}User user = (User) session.getAttribute("user");if (user == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}// 2. 获取到参数中的 blogIdString blogId = req.getParameter("blogId");if (blogId == null || "".equals(blogId)) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前 blogId 参数不对!");return;}// 3. 获取要修改的博客信息.BlogDao blogDao = new BlogDao();BlogId = Integer.parseInt(blogId);Blog blog = blogDao.selectById(Integer.parseInt(blogId));if (blog == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前要修改的博客不存在!");return;}else{resp.setContentType("application/json;charset=utf-8");resp.getWriter().write(objectMapper.writeValueAsString(blog));}}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1. 检查当前用户是否登录req.setCharacterEncoding("utf-8");resp.setContentType("application/json;charset=utf8");HttpSession session = req.getSession(false);if (session == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}User user = (User) session.getAttribute("user");if (user == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}String title = req.getParameter("title");String content = req.getParameter("content");if(title == null || "".equals(title) || content == null || "".equals(content)){resp.getWriter().write("<script>alert('有内容为空')</script>");return;}int blogId = BlogId;BlogDao blogDao = new BlogDao();Blog blog = new Blog();blog.setTitle(title);blog.setContent(content);blog.setBlogId(blogId);blogDao.update(blog);resp.sendRedirect("blog_list.html");}
}
此外,为了能够实现更新功能,在 BlogDao 中新增加了一个 update 方法
public void update(Blog blog) {Connection connection = null;PreparedStatement statement = null;try {// 1. 建立连接connection = DBUtil.getConnection();// 2. 拼装 SQL 语句String sql = "update blog set content = ? ,title = ? where blogId = ?";statement = connection.prepareStatement(sql);statement.setString(1, blog.getContent());statement.setString(2, blog.getTitle());statement.setInt(3, blog.getBlogId());// 3. 执行 SQL 语句int ret = statement.executeUpdate();if (ret == 1) {System.out.println("编辑成功");} else {System.out.println("编辑失败");}} catch (SQLException e) {e.printStackTrace();} finally {DBUtil.close(connection, statement, null);}}
3、前端代码编写
重新编写了一个长的和发布文章类似的页面来实现编辑文章,同时在博客详情页中增加了一个 编辑的按钮
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>博客编辑页</title><link rel="stylesheet" href="CSS/common.css"><link rel="stylesheet" href="CSS/blog_edit.css"><!-- 引入 editor.md 的依赖 --><link rel="stylesheet" href="editor.md/css/editormd.min.css" /><script src="js/jquery.mini.js"></script><script src="editor.md/lib/marked.min.js"></script><script src="editor.md/lib/prettify.min.js"></script><script src="editor.md/editormd.js"></script>
</head>
<body>
<!-- 这是导航栏 -->
<div class="nav"><img src="image/logo2.png" alt=""><span>我的博客系统</span><!-- 空白元素, 用来占位置 --><div class="spacer"></div><a href="blog_list.html">主页</a><a href="blog_edit.html">写博客</a><a href="logout">注销</a>
</div>
<!-- 包裹整个博客编辑页内容的顶级容器 -->
<div class="blog-edit-container"><form action="update" method="post" style="height: 100%"><div class="title"><input type="text" placeholder="在此处输入标题" name="title" id="title"><!--<button>发布文章</button>--><input type="submit" value="提交修改" id="submit"></div><!-- 放置 md 编辑器 --><div id="editor"><!-- 为了进行 form 的提交,此处搞一个 textarea 多行编辑器,借助这个编辑框来实现表单的提交 --><!-- 可以设置 editor.md,让编辑器把 markdown 内容也同步的保存到这个隐藏的 textarea 中,从而进行 form 提交 --><textarea class="content" name="content" style="display: none"></textarea></div></form></div><script>function getEditUpdate(){$.ajax({type: 'get',url: 'update' + location.search,success: function(body){let title = document.querySelector(".title>#title")title.innerHTML = body.title;let content = document.querySelector('.content')content.innerHTML = body.content;}});}getEditUpdate();</script><script>//初始化编辑器let editor = editormd("editor",{//这里的尺寸必须在这里设置,设置样式会被editormd 自动覆盖掉width: "100%",//设定编辑器高度height: "calc(100% - 50px)",//编辑器中的初始内容markdown: "# 在这里写下一篇博客",//指定 editor.md 依赖的插件路径path: "editor.md/lib/",// 此处要加上一个重要的选项,然后 editor.md 就会自动把用户在编辑器输入的内容同步保存到 隐藏的 textarea 中了!saveHTMLToTextarea: true,});
</script>
<!-- <script src="js/common.js"></script>-->
</body>
</html>
4、遇到的问题
在最初代码编写的时候,我直接复用了之前发布文章的页面来实现对文章内容的修改功能,后来发现这样容易使发布功能和编辑功能混淆,最后将两个功能页面分开,重新编写了一个博客编辑的页面
三、实现用户博客总数统计
在目前的代码中,我们的博客总数是固定的,无法实时显示该用户的博客总数,于是我们加一个接口来实现这个功能
1、编写后端代码
@WebServlet("/num")
public class totalServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession(false);if (session == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录!");return;}User user = (User) session.getAttribute("user");if (user == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录!");return;}//确保了登录之后resp.setContentType("text/html;charset=utf8");String blogId = req.getParameter("blogId");BlogDao blogDao = new BlogDao();if (blogId ==null){resp.getWriter().write(blogDao.selectTotal(user.getUserId())+"");}else{Blog blog = blogDao.selectById(Integer.parseInt(blogId));UserDao userDao = new UserDao();User author = userDao.selectById(blog.getUserId());resp.getWriter().write(blogDao.selectTotal(author.getUserId()) + "");}}
}
此外,还在 BlogDao 中新增了一个计算个人文章总数的方法
//6. 计算个人文章的总数public static Integer selectTotal(int userId){Connection connection = null;PreparedStatement statement = null;ResultSet resultSet = null;try {connection = DBUtil.getConnection();String sql = "select count(userId) from blog where userId = ?";statement = connection.prepareStatement(sql);statement.setInt(1,userId);resultSet = statement.executeQuery();return resultSet.getInt(1);} catch (SQLException throwables) {throwables.printStackTrace();}finally {DBUtil.close(connection,statement,resultSet);}return null;}
2、编写前端代码:
在博客详情页和博客列表页中都加入这段代码:
四、删除博客
1、编写后端代码
在 BlogDao 中新增一个删除的方法
public void delete(int blogId){Connection connection = null;PreparedStatement statement = null;try{//1、和数据库建立连接connection = DBUtil.getConnection();//2、构造 sql 语句String sql = "delete from blog where blogId = ?";statement = connection.prepareStatement(sql);statement.setInt(1,blogId);//3、执行 sqlstatement.executeUpdate();} catch (SQLException e) {throw new RuntimeException(e);}finally {//进行关闭DBUtil.close(connection,statement,null);}}
@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession(false);if (session == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,不能进行删除操作!");return;}User user = (User) session.getAttribute("user");if (user == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,不能进行删除操作!");return;}//获取 BlogIdString blogId = req.getParameter("blogId");if (blogId == null || "".equals(blogId)){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前 blogId 参数不对!");return;}//获取要删除的博客信息BlogDao blogDao = new BlogDao();Blog blog = blogDao.selectById(Integer.parseInt(blogId));if (blog == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前要删除的博客不存在,blogId = " + blogId);return;}//删除博客内容blogDao.delete(Integer.parseInt(blogId));//回到博客列表页resp.sendRedirect("blog_list.html");}
}
2、编写前端代码
前端代码与前面的同理
3、遇到的问题
在写完代码之后,对页面进行了测试,发现:虽然可以修改代码,但是无法将原先的文章内容进行回显,于是我对前端代码进行了微调,实现回显功能
1、在 title 和 content 中加入 value 属性
2、在函数中修改 title 和 content 的赋值方式,使用 value 进行赋值
四、编辑博客
思路:
在博客详情页点击编辑博客之后,自动跳转到编辑页面,同时将原先的博客内容回显到 markdown 编辑器上,然后对原文进行编辑之后,再次提交修改即可
1、后端代码
@WebServlet("/update")
public class updateServlet extends HttpServlet {private ObjectMapper objectMapper = new ObjectMapper();private int BlogId = 0;protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1. 检查当前用户是否登录resp.setContentType("application/json;charset=utf-8");HttpSession session = req.getSession(false);if (session == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}User user = (User) session.getAttribute("user");if (user == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}// 2. 获取到参数中的 blogIdString blogId = req.getParameter("blogId");if (blogId == null || "".equals(blogId)) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前 blogId 参数不对!");return;}// 3. 获取要修改的博客信息.BlogDao blogDao = new BlogDao();BlogId = Integer.parseInt(blogId);Blog blog = blogDao.selectById(Integer.parseInt(blogId));if (blog == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前要修改的博客不存在!");return;}else{resp.setContentType("application/json;charset=utf-8");resp.getWriter().write(objectMapper.writeValueAsString(blog));}}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 1. 检查当前用户是否登录req.setCharacterEncoding("utf-8");resp.setContentType("application/json;charset=utf8");HttpSession session = req.getSession(false);if (session == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}User user = (User) session.getAttribute("user");if (user == null) {resp.setContentType("text/html; charset=utf8");resp.getWriter().write("当前尚未登录, 不能修改!");return;}String title = req.getParameter("title");String content = req.getParameter("content");if(title == null || "".equals(title) || content == null || "".equals(content)){resp.getWriter().write("<script>alert('有内容为空')</script>");return;}int blogId = BlogId;BlogDao blogDao = new BlogDao();Blog blog = new Blog();blog.setTitle(title);blog.setContent(content);blog.setBlogId(blogId);blogDao.update(blog);resp.sendRedirect("blog_list.html");}
}
2、前端代码
五、管理员审核博客
1、后端代码
@WebServlet("/admin")
public class adminServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession(false);if (session == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,无法进行审核");return;}User user = (User) session.getAttribute("user");if (user == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,无法进行审核");return;}String blogId = req.getParameter("blogId");BlogDao blogDao = new BlogDao();ObjectMapper objectMapper = new ObjectMapper();if (blogId == null){//query string 不存在,则是审核详情页列表页List<Blog> blogs = blogDao.selectAudit();String respJson = objectMapper.writeValueAsString(blogs);resp.setContentType("application/json;charset=utf8");resp.getWriter().write(respJson);}else {//query string 存在,则是审核详情页Blog blog = blogDao.selectById(Integer.parseInt(blogId));String respJson = objectMapper.writeValueAsString(blog);resp.setContentType("application/json;charset=utf8");resp.getWriter().write(respJson);}}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//审核通过的 post 请求HttpSession session = req.getSession(false);if (session == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,无法进行审核");return;}User user = (User) session.getAttribute("user");if (user == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,无法进行审核");return;}Blog blog = new Blog();String blogId = req.getParameter("blogId");BlogDao blogDao = new BlogDao();blogDao.changeStatus(Integer.parseInt(blogId),1);resp.sendRedirect("admin_list.html");}
}
@WebServlet("/false")
public class falseServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//审核不通过的 post 请求HttpSession session = req.getSession(false);if (session == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,无法进行审核");return;}User user = (User) session.getAttribute("user");if (user == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前未登录,无法进行审核");return;}Blog blog = new Blog();String blogId = req.getParameter("blogId");BlogDao blogDao = new BlogDao();blogDao.changeStatus(Integer.parseInt(blogId),-1);resp.sendRedirect("admin_list.html");}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//统计审核通过了的文章总数并返回HttpSession session = req.getSession(false);if (session == null) {resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录!");return;}User user = (User) session.getAttribute("user");if (user == null) {resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录!");return;}//确保了登录之后resp.setContentType("text/html;charset=utf8");String blogId = req.getParameter("blogId");BlogDao blogDao = new BlogDao();int num = blogDao.countSuccess();resp.getWriter().write(num + "");}
}
2、前端代码
前端代码与之前的差不多,这里就只展示一部分
六、评论
1、后端代码
@WebServlet("/comments")
public class commentsServlet extends HttpServlet {public int blogId;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ObjectMapper objectMapper = new ObjectMapper();HttpSession session = req.getSession(false);if (session == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录!");return;}User user = (User) session.getAttribute("user");if (user == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录!");return;}CommentsDao commentsDao = new CommentsDao();blogId = Integer.parseInt(req.getParameter("blogId"));List<Comments> commentsList = commentsDao.selectAll(blogId);//把 数据 转换成 json 格式String respJson = objectMapper.writeValueAsString(commentsList);resp.setContentType("application/json;charset=utf8");resp.getWriter().write(respJson);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {HttpSession session = req.getSession(false);if (session == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录,不能发表评论!");return;}User user = (User) session.getAttribute("user");if (user == null){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前用户未登录,不能发表评论!");return;}//获取评论信息req.setCharacterEncoding("utf8");String content = req.getParameter("content");if (content == null || "".equals(content)){resp.setContentType("text/html;charset=utf8");resp.getWriter().write("当前提交数据为空!");return;}//在博客详情页,对//构造 comments 对象String blogId = req.getParameter("blogId");Comments comments = new Comments();comments.setContent(content);comments.setPostTime(new Timestamp(System.currentTimeMillis()));comments.setBlogId(Integer.parseInt(blogId));//插入数据CommentsDao commentsDao = new CommentsDao();commentsDao.add(comments);//跳转到博客列表页resp.sendRedirect("blog_list.html");}
}
2、前端代码
在博客详情页添加了一个小方块来放置评论,同时在详情页的最底下增加提交评论的功能
七、统计
在普通用户页面计算通过审核的文章和未通过审核的文章,在管理员页面计算待审核的文章和审核成功的文章个数
主要通过 status 列来进行统计,这里就不再展示代码了