基于spring实现博客项目的删除和更新(五)

8. 实现用户退出

        前端直接清除掉token即可.

        实现客⼾端代码

        <注销>链接已经提前添加了onclick事件 ,在common.js中完善logout⽅法  

function logout(){
    localStorage.removeItem("user_token");
    location.href = "blog_login.html";
}

        点击下图注销:

        返回到登录页面:

localstorage中的令牌也被清除掉了;

9.  实现发布博客

9.1 约定前后端交互接⼝

[请求]
/blog/add
title=标题&content=正⽂...
[响应]
{
 "code": 200,
 "msg": "",
 "data": true
}
//true 成功
//false 失败

9.2 实现服务器代码

        修改 BlogController, 新增 add ⽅法.

   @RequestMapping("/add")
    public Result insert(String title, String content, HttpServletRequest request){
        //获取当前登录⽤⼾ID
        String jwtToken = request.getHeader("user_token");
        Integer loginUserId = JwtUtils.getUserIdFromToken(jwtToken);
        if (loginUserId==null || loginUserId<1){
            return Result.fail(-1,"⽤⼾未登录");
        }
        Blog blog = new Blog();
        blog.setUserId(loginUserId);
        blog.setTitle(title);
        blog.setContent(content);
        blogService.insertBlog(blog);
        return Result.success(true);
    }

         BlogService 添加对应的处理逻辑

   public int insertBlog(Blog record){
        return blogMapper.insertBlog(record);
    }

 9.2.1 editor.md 简单介绍

        editor.md 是⼀个开源的⻚⾯ markdown 编辑器组件. 官⽹参⻅: http://editor.md.ipandao.com/ 代码: https://pandao.github.io/editor.md/ 使⽤⽰例

<link rel="stylesheet" href="editormd/css/editormd.css" />
<div id="test-editor">
 <textarea style="display:none;">### 关于 Editor.md
**Editor.md** 是⼀款开源的、可嵌⼊的 Markdown 在线编辑器(组件),基于 CodeMirror、
jQuery 和 Marked 构建。
 </textarea>
</div>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="editormd/editormd.min.js"></script>
<script type="text/javascript">
 $(function() {
 var editor = editormd("test-editor", {
 // width : "100%",
 // height : "100%",
 path : "editormd/lib/"
 });
 });
</script>

        使⽤时引⼊对应依赖就可以了

        "test-editor" 为 markdown编辑器所在的div的id名称

        path为 editor.md依赖所在的路径 

9.3 实现客⼾端代码

        修改 blog_edit.html • 完善submit⽅法 

 function submit() {
            $.ajax({
                type:"post",
                url: "/blog/add",
                data:{
                    title:$("#title").val(),
                    content:$("#content").val()
                },
                success:function(result){
                    if(result.code==200 && result.data==true){
                        location.href = "blog_list.html";
                    }
                    //结果为false, 下面自己补充
                    else{
                        alert(result.msg);
                        return;
                    }
                },
                error:function(error){
                    if(error!=null && error.status==401){
                        alert("⽤⼾未登录, 登录后再进⾏对应操作")
                    }
                }
            });
        }

        如下图所示,我们发现我们的blog在发布之后,在博客列表和内容细节页正文部分带有一些符号:

        修改详情⻚⻚⾯显⽰ ,即详情⻚会显⽰markdown的格式符号, 我们对⻚⾯进⾏也下处理 

1. 修改 html 部分, 把博客正⽂的 div 标签, 改成如下内容,并且加上 style="background-color: transparent;"

<!-- 右侧内容详情 -->
<div class="content">
 <div class="title"></div>
 <div class="date"></div>
 <div class="detail" id="detail" style="background-color: transparent;">
 </div>
 <div class="operating">
 <button onclick="window.location.href='blog_update.html'">编辑</button>
 <button>删除</button>
 </div>
</div>

2. 修改博客正⽂内容的显⽰

 $.ajax({
            type: "get",
            url: "/blog/getBlogDetail" + location.search,
            success: function (result){
                console.log(result);
                if(result.code == 200 && result.data != null){
                    $(".title").text(result.data.title);
                    $(".date").text(result.data.createTime);
                    // $(".detail").text(result.data.content);
                    editormd.markdownToHTML("detail", {
                        markdown: result.data.content,
                    });
                }
            },

         我们之前存在问题的页面被成功如下修正;

10. 实现删除/编辑博客

        进⼊⽤⼾详情⻚时, 如果当前登陆⽤⼾正是⽂章作者, 则在导航栏中显⽰ [编辑] [删除] 按钮, ⽤⼾点击时 则进⾏相应处理.

        需要实现两件事:

        1、 判定当前博客详情⻚中是否要显⽰[编辑] [删除] 按钮

        2、实现编辑/删除逻辑. 删除采⽤逻辑删除, 所以和编辑其实为同⼀个接⼝

10.1 约定前后端交互接⼝

        1. 判定是否要显⽰[编辑] [删除] 按钮

        即修改之前的获取博客信息的接⼝, 在响应中加上⼀个字段.

        loginUser 为 1 表⽰当前博客就是登陆⽤⼾⾃⼰写的.

[请求]
/blog/getBlogDetail?blogId=1
[响应]
{
 "code": 200,
 "msg": "",
 "data": {
"id": 1,
 "title": "第⼀篇博客",
 "content": "111我是博客正⽂我是博客正⽂我是博客正⽂",
 "userId": 1,
 "loginUser": 1
 "deleteFlag": 0,
 "createTime": "2023-10-21 16:56:57",
 "updateTime": "2023-10-21T08:56:57.000+00:00"
 }
}

2. 修改博客

[请求]
/blog/update
[参数]
Content-Type: application/json
{
 "title": "测试修改⽂章",
 "content": "在这⾥写下⼀篇博客",
 "blogId": "4"
}
[响应]
{
 "code": 200,
 "msg": "",
 "data": true
}

3、删除博客

[请求]
/blog/delete?blogId=1
[响应]
{
 "code": 200,
 "msg": "",
 "data": true
}

10.2 实现服务器代码

        1. 给Blog类新增⼀个字段

@Data
public class Blog {
    private Integer id;
    private String title;
    private String content;
    private Integer userId;
    private Integer deleteFlag;
    private Date createTime;
    private Date updateTime;
    private Integer loginUser;
    public String getCreateTime(){
        return DateUtils.format(createTime);
    }
}

        2. 修改 BlogController 其他代码不变. 只处理 "getBlogDeatail" 中的逻辑.从请求中获取登录用户的userid,如果登录用户和文章的作者是同一个人的话就给新变量赋值为1;

  @RequestMapping("/getBlogDetail")
    public Blog getBlogDetail(Integer blogId,HttpServletRequest request){
        Blog blog = blogService.getBlogDetail(blogId);
        String jwtToken = request.getHeader("user_token");
        Integer loginUserId = JwtUtils.getUserIdFromToken(jwtToken);
        if (loginUserId!=null && blog.getUserId()==loginUserId){
            blog.setLoginUser(1);
        }
        return blog;
    }

3. 修改 BlogController

        增加 update/delete ⽅法, 处理修改/删除逻辑.

@RequestMapping("/update")
    public Result update(@RequestBody Blog blog){
        blogService.updateBlog(blog);
        return Result.success(true);
    }
    @RequestMapping("/delete")
    public boolean delete(Integer blogId){
        Blog blog = new Blog();
        blog.setId(blogId);
        blog.setDeleteFlag(1);
        blogService.updateBlog(blog);
        return true;
    }
 public Integer updateBlog(Blog blog) {
        return blogMapper.updateBlog(blog);
    }

10.3 实现客⼾端代码

        1. 判断是否显⽰[编辑] [删除]按钮

 //获取博客详情
        $.ajax({
            type: "get",
            url: "/blog/getBlogDetail" + location.search,
            success: function (result){
                console.log(result);
                if(result.code == 200 && result.data != null){
                    $(".title").text(result.data.title);
                    $(".date").text(result.data.createTime);
                    // $(".detail").text(result.data.content);
                    editormd.markdownToHTML("detail", {
                        markdown: result.data.content,
                    });
                    // 是否显示编辑/删除按钮
                    if(result.data.loginUser){
                        console.log("显示编辑/删除");
                        var html = "";
                        html += '<div class="operating">';
                        html += '<button onclick="window.location.href=\'blog_update.html'+location.search+'\'">编辑</button>';
                        html += '<button onclick="deleteBlog()">删除</button>';
                        html += '</div>';
                        $(".content").append(html);
                    }
                }
            },
            error:function (error){
                console.log(error);
                if(error!=null && error.status==401){
                    alert("⽤⼾未登录, 即将跳转到登录⻚!");
                    //已经被拦截器拦截了, 未登录
                    location.href ="blog_login.html";
                }
            }
        })
        //显⽰当前登录⽤⼾的信息
        function deleteBlog() {
            if(confirm("确定删除这篇博客吗?")){
                $.ajax({
                type:"post",
                url:"/blog/delete"+location.search,
                success:function(result){
                    if(result.code==200 && result.data==true){
                        alert("删除成功, 即将跳转⾄博客列表⻚");
                        location.href = "blog_list.html";
                    }else{
                        alert("删除失败");
                    }

                }
            });
            }
        }

         编辑博客逻辑:

        修改blog_update.html ⻚⾯加载时, 请求博客详情

    function getBlogInfo() {
            $.ajax({
                type:"get",
                url:"/blog/getBlogDetail"+location.search,
                success:function(result){
                    if (result.code == 200 && result.data != null) {
                        console.log(result);
                        $("#blogId").val(result.data.id);
                        $("#title").val(result.data.title);
                        // $("#content").val(result.data.content);
                        editormd("editor", {
                            width  : "100%",
                            height : "550px",
                            path: "blog-editormd/lib/",
                            onload : function() {
                                this.watch()
                                this.setMarkdown(result.data.content);
                            }
                        });
                    }
                },
                error: function (err) {
                    if (err != null && err.status == 401) {
                        alert("⽤⼾未登录, 即将跳转到登录⻚!");
                        //已经被拦截器拦截了, 未登录
                        location.href = "/blog_login.html";
                    }
                }

            });
        }
        getBlogInfo();

        已经在getBlogInfo进⾏markdown编辑器的渲染了, 所以把以下代码删除

$(function () {
 var editor = editormd("editor", {
 width: "100%",
 height: "550px",
 path: "blog-editormd/lib/"
 });
});

         完善发表博客的逻辑

function submit() {
            $.ajax({
                type: "post",
                url: "/blog/update",
                contentType: "application/json",
                data: JSON.stringify({
                    "title": $("#title").val(),
                    "content": $("#content").val(),
                    "id": $("#blogId").val()
                }),
                success: function (result) {
                    if (result != null && result.code == 200 && result.data == true) {
                        location.href = "blog_list.html";
                    } else {
                        alert(result.msg);
                        return;
                    }
                },
                error: function (error) {
                    if (error != null && error.status == 401) {
                        alert("⽤⼾未登录, 登录后再进⾏对应操作");
                    }
                }
            });
        }

        运行程序: 

修改之前:

修改之后:

删除之前:

删除之后:

        点击删除按钮:

点击确定:

进入到博客列表页:

        由此删除成功;

        本文就到这里了,谢谢观看!!!

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值