您好,欢迎来到华佗养生网。
搜索
您的当前位置:首页创建个人中心页面

创建个人中心页面

来源:华佗养生网

页面设计

在数据库中创建表bot

表中包含的列:

id: int:非空、自动增加、唯一、主键
user_id: int:非空
注意:在pojo中需要定义成userId,在queryWrapper中的名称仍然为user_id
title: varchar(100)
description: varchar(300)
content:varchar(10000)
rating: int:默认值为1500
createtime: datetime
pojo中定义日期格式的注解:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
modifytime: datetime
pojo中定义日期格式的注解:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")

实现后端API

/user/bot/add/:创建一个Bot
/user/bot/remove/:删除一个Bot
/user/bot/update/:修改一个Bot
/user/bot/getlist/:查询Bot列表

pojo层

Bot.java

package com.kob.backend.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bot {
    //主键自增
    @TableId(type = IdType.AUTO)
    private Integer id;
    private Integer userId;
    private String title;
    private String description;
    private String content;
    private Integer rating;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Data createtime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Data modifytime;
}

mapper层

BotMapper.java

package com.kob.backend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kob.backend.pojo.Bot;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface BotMapper extends BaseMapper<Bot> {

}

Service层 

 定义BotMapper接口

package com.kob.backend.service.user.bot;

import java.util.Map;

public interface AddService {
    Map<String,String>  add(Map<String,String> data);
}
package com.kob.backend.service.user.bot;

import com.kob.backend.pojo.Bot;

import java.util.List;

public interface GetListService {
    List<Bot> getList();
}

package com.kob.backend.service.user.bot;

import java.util.Map;

public interface RemoveService {
    Map<String,String>  remove(Map<String,String> data);
}

package com.kob.backend.service.user.bot;

import java.util.Map;

public interface UpdateService {
    Map<String,String> update(Map<String,String> data);
}

 实现接口:

package com.kob.backend.service.impl.user.bot;

import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AddServiceImpl implements AddService {

    @Autowired
    private BotMapper botMapper;

    @Override
    public Map<String, String> add(Map<String, String> data) {
        //获取用户信息
        UsernamePasswordAuthenticationToken authenticationToken=
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser=(UserDetailsImpl) authenticationToken.getPrincipal();
        User user=loginUser.getUser();

        String title=data.get("title");
        String description=data.get("description");
        String content=data.get("content");

        Map<String,String> map=new  HashMap<>();
        if(title==null||title.length()==0){
            map.put("error_message","标题不能为空");
            return map;
        }
        if(title.length()>100){
            map.put("error_message","标题的长度不能大于100");
            return map;
        }
        if(description.length()==0){
            description="这个用户很懒什么也没留下";
        }
        if (description.length()>300){
           map.put("error_message","Bot的描述的长度不能大于300");
           return map;
        }
        if(content==null&&content.length()==0){
            map.put("error_message","代码不能为空");
            return map;
        }
        if (content.length()>10000){
            map.put("error_message","代码长度不能超过10000");
            return map;
        }

        Date now=new Date();
        Bot bot=new Bot(null, user.getId(), title,description,content,1500,now,now);

        botMapper.insert(bot);
        map.put("error_message","success");


        return map;
    }
}
package com.kob.backend.service.impl.user.bot;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.GetListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class GetListServiceImpl implements GetListService {
    //获取bot数据库的查询接口
    @Autowired
    private BotMapper botMapper;

    @Override
    public List<Bot> getList() {
        UsernamePasswordAuthenticationToken authenticationToken =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();
        //查询条件
        QueryWrapper<Bot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());

        return botMapper.selectList(queryWrapper);
    }
}

package com.kob.backend.service.impl.user.bot;


import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.RemoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RemoveServiceImpl implements RemoveService {

    @Autowired
    private BotMapper botMapper;
    @Override
    public Map<String, String> remove(Map<String, String> data) {
        UsernamePasswordAuthenticationToken authenticationToken=
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginuser=(UserDetailsImpl) authenticationToken.getPrincipal();
        User user=loginuser.getUser();
        int bot_id=  Integer.parseInt(data.get("bot_id"));
        Bot bot=botMapper.selectById(bot_id);
        Map<String,String> map=new HashMap<>();
        if(bot==null){
            map.put("error_message","Bot不存在或已被删除");
            return map;
        }
        if (!bot.getUserId().equals(user.getId())){
            map.put("error_message","没有权限删除该Bot");
            return map;
        }
        botMapper.deleteById(bot_id);
        map.put("error_massage","success");

        return map;
    }
}
package com.kob.backend.service.impl.user.bot;

import com.kob.backend.mapper.BotMapper;
import com.kob.backend.pojo.Bot;
import com.kob.backend.pojo.User;
import com.kob.backend.service.impl.utils.UserDetailsImpl;
import com.kob.backend.service.user.bot.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service
public class UpdateServiceImpl implements UpdateService {
    @Autowired
    private BotMapper botMapper;
    @Override
    public Map<String, String> update(Map<String, String> data) {
        UsernamePasswordAuthenticationToken authenticationToken=
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser= (UserDetailsImpl) authenticationToken.getPrincipal();
        User user=loginUser.getUser();
        int bot_id=Integer.parseInt(data.get("bot_id"));

        //传回的数据
        String title=data.get("title");
        String description=data.get("description");
        String content=data.get("content");
        Map<String,String> map=new HashMap<>();

        if(title==null||title.length()==0){
            map.put("error_message","标题不能为空");
            return map;
        }
        if(title.length()>100){
            map.put("error_message","标题的长度不能大于100");
            return map;
        }
        if(description.length()==0){
            description="这个用户很懒什么也没留下";
        }
        if (description.length()>300){
            map.put("error_message","Bot的描述的长度不能大于300");
            return map;
        }
        if(content==null&&content.length()==0){
            map.put("error_message","代码不能为空");
            return map;
        }
        if (content.length()>10000){
            map.put("error_message","代码长度不能超过10000");
            return map;
        }
        Bot bot=botMapper.selectById(bot_id);
        if (bot==null){
            map.put("error_message","Bot不存在或已经被删除");
            return map;
        }
        if(!bot.getUserId().equals(user.getId())){
            map.put("error_message","没有权限修改该Bot");
            return map;
        }
        Bot new_bot=new Bot(
                bot.getId(),
                user.getId(),
                title,
                description,
                content,
                bot.getRating(),
                bot.getCreatetime(),
                new Date()
        );
        botMapper.updateById(new_bot);
        map.put("error_message","success");
        return map;
    }
}

Controller层

package com.kob.backend.controller.user.bot;

import com.kob.backend.service.user.bot.AddService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class AddController {
    @Autowired
    private AddService addService;


    @PostMapping("/user/bot/add")
    public Map<String,String> add(@RequestParam Map<String,String> data){
        return addService.add(data);
    }

}
package com.kob.backend.controller.user.bot;

import com.kob.backend.pojo.Bot;
import com.kob.backend.service.user.bot.GetListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class GetListController {
    @Autowired
    private GetListService getListService;

    @GetMapping("/user/bot/getlist/")
    public List<Bot> getList() {
        return getListService.getList();
    }
}
package com.kob.backend.controller.user.bot;

import com.kob.backend.service.user.bot.RemoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class RemoveController {
    @Autowired
    private RemoveService removeService;

    @PostMapping("/user/bot/remove/")
    public Map<String,String> remove(@RequestParam Map<String,String> data){
        return  removeService.remove(data);
    }


}
package com.kob.backend.controller.user.bot;

import com.kob.backend.service.user.bot.UpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class UpdateController {
    @Autowired
    private UpdateService updateService;

    @PostMapping("/user/bot/update")
    public Map<String,String> update(@RequestParam Map<String,String> data){
            return updateService.update(data);
    }
}

实现前端界面

实现code编辑器

import { VAceEditor } from 'vue3-ace-editor';
import ace from 'ace-builds';
ace.config.set(
    "basePath", 
    "https://cdn.jsdelivr.net/npm/ace-builds@" + require('ace-builds').version + "/src-noconflict/")
<VAceEditor
    v-model:value="botadd.content"
    @init="editorInit"
    lang="c_cpp"
    theme="textmate"
    style="height: 300px" />

安装依赖:        

注:vue3中绑定一个对象用reactive,绑定一个变量的话用ref     

 优化:

import { VAceEditor } from "vue3-ace-editor";
import ace from "ace-builds";

import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-chrome';
import 'ace-builds/src-noconflict/ext-language_tools';


    ace.config.set(
      "basePath",
      "https://cdn.jsdelivr.net/npm/ace-builds@" +
        require("ace-builds").version +
        "/src-noconflict/"


<VAceEditor
            v-model:value="formState.bot.content"
            @init="editorInit"
            lang="c_cpp"
            theme="textmate"
            style="height: 300px"
            :options="{
              enableBasicAutocompletion: true, //启用基本自动完成
              enableSnippets: true, // 启用代码段
              enableLiveAutocompletion: true, // 启用实时自动完成
              fontSize: 14, //设置字号
              tabSize: 2, // 标签大小
              showPrintMargin: false, //去除编辑器里的竖线
              highlightActiveLine: true,
            }"
          />
<template>
    <div class="container">
        <div class="row">
            <div class="col-3">
                <div class="card" style="margin-top: 20px;">
                    <div class="card-body">
                        <img :src="$store.state.user.photo" alt="" >
                    </div>
                </div>
            </div>
            <div class="col-9">
                <div class="card" style="margin-top: 20px;">
                    <div class="card-header">
                        <span style="font-size: 140%;">
                            我的Bot
                        </span>
                         <!-- Button trigger modal -->
                        <button type="button" class="btn btn-outline-primary float-end" 
                         data-bs-toggle="modal" data-bs-target="#add-bot-btn">
                            创建Bot
                        </button>
                        <!-- Modal -->
                        <div class="modal fade" id="add-bot-btn" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                            <div class="modal-dialog modal-xl">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h1 class="modal-title fs-5" id="staticBackdropLabel">创建Bot</h1>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <!-- 表单 -->
                                        <form>
                                            <div class="mb-3">
                                                <label for="add-bot-title" class="form-label">名称</label>
                                                <input v-model="botadd.title" type="text" class="form-control" id="add-bot-title" placeholder="请输入Bot名称">
                                            </div>
                                            <div class="mb-3">
                                                <label for="add-bot-description" class="form-label">简介</label>
                                                <textarea v-model="botadd.description" type="password" class="form-control" id="add-bot-description" placeholder="请输入Bot简介"></textarea>
                                            </div>
                                            <div class="mb-3">
                                                <label for="add-bot-code" class="form-label">代码</label>
                                                <!-- <textarea v-model="botadd.content" type="password" class="form-control" id="add-bot-code" placeholder="请编写Bot代码"></textarea> -->
                                                <VAceEditor
                                                    v-model:value="botadd.content"
                                                    @init="editorInit"
                                                    lang="c_cpp"
                                                    theme="textmate"
                                                    style="height: 300px"
                                                    :options="{
                                                    enableBasicAutocompletion: true, //启用基本自动完成
                                                    enableSnippets: true, // 启用代码段
                                                    enableLiveAutocompletion: true, // 启用实时自动完成
                                                    fontSize: 14, //设置字号
                                                    tabSize: 2, // 标签大小
                                                    showPrintMargin: false, //去除编辑器里的竖线
                                                    highlightActiveLine: true,
                                                    }"
                                                />
                                            </div>
                                        </form>
                                    </div>
                                    <div class="modal-footer">
                                        <div class="error_message">{{ botadd.error_message }}</div>
                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                        <button type="button" class="btn btn-primary" @click="add_bot">创建</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>名称</th>
                                    <th>创建时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="bot in bots" :key="bot.id">
                                    <td> {{ bot.title }}</td>
                                    <td>{{ bot.createtime }}</td>
                                    <td>
                                        <button type="button" class="btn btn-outline-secondary "  style="margin-right: 10px;"  data-bs-toggle="modal" :data-bs-target="'#update-bot-modal-'+bot.id" >  修改  </button>
                                        <button type="button" class="btn btn-danger" @click="remove_bot(bot)">删除</button>
                                        <!-- Modal -->
                                        <div class="modal fade" :id="'update-bot-modal-'+bot.id" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                                            <div class="modal-dialog modal-xl">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h1 class="modal-title fs-5" id="staticBackdropLabel">创建Bot</h1>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <!-- 表单 -->
                                                        <form>
                                                            <div class="mb-3">
                                                                <label for="update-bot-title" class="form-label">名称</label>
                                                                <input v-model="bot.title" type="text" class="form-control" id="update-bot-title" placeholder="请输入Bot名称">
                                                            </div>
                                                            <div class="mb-3">
                                                                <label for="update-bot-description" class="form-label">简介</label>
                                                                <textarea v-model="bot.description" type="password" class="form-control" id="update-bot-description" placeholder="请输入Bot简介"></textarea>
                                                            </div>
                                                            <div class="mb-3">
                                                                <label for="update-bot-code" class="form-label">代码</label>
                                                                <VAceEditor
                                                                    v-model:value="bot.content"
                                                                    @init="editorInit"
                                                                    lang="c_cpp"
                                                                    theme="textmate"
                                                                    style="height: 300px"
                                                                    :options="{
                                                                        enableBasicAutocompletion: true, //启用基本自动完成
                                                                        enableSnippets: true, // 启用代码段
                                                                        enableLiveAutocompletion: true, // 启用实时自动完成
                                                                        fontSize: 14, 
                                                                        tabSize: 2, // 标签大小
                                                                        showPrintMargin: false, //去除编辑器里的竖线
                                                                        highlightActiveLine: true,
                                                                    }"
                                                                />
                                                            </div>
                                                        </form>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <div class="error_message">{{ botadd.error_message }}</div>
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                                        <button type="button" class="btn btn-primary" @click="update_bot(bot)">保存修改</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {ref,reactive} from 'vue';
import { useStore } from "vuex";
import $ from "jquery";
import {Modal} from 'bootstrap/dist/js/bootstrap';
import { VAceEditor } from 'vue3-ace-editor';
import ace from 'ace-builds';
import 'ace-builds/src-noconflict/mode-c_cpp';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-chrome';
import 'ace-builds/src-noconflict/ext-language_tools';
export default{
    components: {
        VAceEditor
    },
    setup() {
        ace.config.set(
            "basePath",
            "https://cdn.jsdelivr.net/npm/ace-builds@" +
                require("ace-builds").version +
                "/src-noconflict/")

        const store=useStore();
        let bots=ref([]);

        const botadd=reactive({
            title:"",
            description:"",
            content: "",
            error_message:"",
        });
        //刷新列表函数
        const refresh_bot=()=>{
            $.ajax({
                type: "get",
                url: "http://127.0.0.1:8080/user/bot/getlist/",
                headers: {
                Authorization: "Bearer " + store.state.user.token,
                },
                success: function (resp) {
                    bots.value=resp;
                },
                
            })
        }
        refresh_bot();

        //创建bot事件,向后端添加Bot
        const add_bot=()=>{
            botadd.error_message="";
            $.ajax({
                type: "post",
                url: "http://127.0.0.1:8080/user/bot/add/",
                data: {
                    title:botadd.title,
                    description:botadd.description,
                    content:botadd.content,
                },
                headers: {
                    Authorization: "Bearer " + store.state.user.token,
                },
                success: function (resp) {
                    if(resp.error_message==="success"){
                        botadd.title="";
                        botadd.content="";
                        botadd.description="";
                        Modal.getInstance("#add-bot-btn").hide();
                        refresh_bot();
                    }else{
                        botadd.error_message=resp.error_message;    
                    }
                },
            });
        }
        const remove_bot=(bot)=>{
            $.ajax({
                type: "post",
                url: "http://127.0.0.1:8080/user/bot/remove/",
                data: {
                    bot_id:bot.id,
                },
                headers: {
                    Authorization: "Bearer " + store.state.user.token,
                },
                success: function (resp) {
                    if(resp.error_message==="success"){
                        refresh_bot();
                    }
                },
            });
        }
        const update_bot=(bot)=>{
            $.ajax({
                type: "post",
                url: "http://127.0.0.1:8080/user/bot/update/",
                data: {
                    bot_id:bot.id,
                    title:bot.title,
                    description:bot.description,
                    content:bot.content,
                },
                headers: {
                    Authorization: "Bearer " + store.state.user.token,
                },
                success: function (resp) {
                    if(resp.error_message==="success"){
                        Modal.getInstance('#update-bot-modal-'+bot.id).hide();
                        refresh_bot();
                    }
                },
                error(resp){
                    console.log(resp);
                }
         });
        }
        return{
            bots,
            botadd,
            add_bot,
            remove_bot,
            refresh_bot,
            update_bot,
        }

    }
}
</script>

<style scoped>
img{
    width: 180px;
    height: 180px;
}
div.error_message{
    color: red;
}
</style>

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo7.cn 版权所有 湘ICP备2022005869号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务