博客系统的后端设计(八) - 实现发布博客功能

发布博客


在原来的编辑页面点击发布文章按钮,是不会有什么效果的。
这是因为此时还不能实现前后端的交互。

1. 约定前后端交互接口

请求使用 POST,路径是 /blog
title=这是标题&content=这是正文

请求中要有 body,按照 form 表单的方式添加进去。

响应使用 HTTP/1.1 302
跳转到列表页:Location: blog.list.html

在一篇博客当中,它有 blogId、title、content、userId、postTime 属性。
只有 title 和 content 是需要自己获取的,blogId 是自增主键,数据库会自己生成;
userId 是作者信息,看提交博客的用户是谁,直接从会话中拿即可;
postTime 是当前的时间。

2. 服务器代码


在之前实现好的 BlogServlet 类中重写一个 doPost 方法。

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
     // 发布博客
     // 读取请求,构造 Blog 对象,插入数据库即可
     HttpSession httpSession = req.getSession(false);
     if (httpSession == null) {
    
    
         // 未登录
         resp.setContentType("text/html; charset=utf8");
         resp.getWriter().write("当前未登录,无法发布博客!!!");
         return;
     }
     User user = (User) httpSession.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.setContentType("text/html; charset=utf8");
         resp.getWriter().write("当前提交的数据有误,标题或正文为空!!!");
         return;
     }

     // 构造 Blog 对象
     Blog blog = new Blog();
     blog.setTitle(title);
     blog.setContent(content);
     blog.setUserId(user.getUserId());
     // 发布时间在 java 中生成/数据库都可以
     blog.setPostTime(new Timestamp(System.currentTimeMillis()));
     // 插入数据库
     BlogDao blogDao = new BlogDao();
     blogDao.add(blog);

     // 跳转到博客列表页
     resp.sendRedirect("blog.list.html");
 }

3. 客户端代码


将之前的写的编辑区容器代码改为以下代码。

<!-- 编辑区容器 -->
<div class="blog-edit-container">
    <form action="blog" method="post">
        <!-- 博客标题编辑区 -->
        <div class="title">
            <input type="text" id="title" placeholder="请输入文章标题" name="title">
            <input type="submit" id="submit" value="发布文章">
        </div>

        <!-- 博客编辑器 是为了和 markdrow 编辑器对接而设置的-->
        <div id="editor">
            <textarea name="content" style="display: none"></textarea>
        </div>
    </form>
</div>

4. 出现的问题


接下来启动服务器,在用户登录后发布一个博客。此时可以看到虽然自动跳转到了列表页,但是出现乱码了。



发布博客后发现乱码了,此时考虑乱码是提交的时候乱的,还是获取的时候乱的。

如果是提交的时候乱的,只需要看一下数据库是不是乱的;此处应该是提交的的时候乱的,
因为提交功能是新写的,还没有测试过,获取博客已经测试过了。


查看数据库后可以看到此时的数据库是乱的。


解决:

先将乱码的记录删除,之后在指定字符集。





此时文章发布成功。

猜你喜欢

转载自blog.csdn.net/m0_63033419/article/details/130822061
今日推荐