SpringBoot学习笔记-创建个人中心页面(上)

news/2024/7/10 2:06:55 标签: spring boot, java, vue, mybatis, 后端

笔记内容转载自 AcWing 的 SpringBoot 框架课讲义,课程链接:AcWing SpringBoot 框架课。

CONTENTS

  • 1. 更新数据库表
  • 2. 实现后端API

1. 更新数据库表

我们需要创建一个表来保存 Bot 的信息,新建一个 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

可以使用如下 SQL 语句一键创建好该表:

CREATE TABLE `kob`.`bot` (
    `id` int NOT NULL AUTO_INCREMENT,
    `user_id` int NOT NULL,
    `title` varchar(100) NULL,
    `description` varchar(300) NULL,
    `content` varchar(10000) NULL,
    `rating` int NULL DEFAULT 1500,
    `createtime` datetime NULL,
    `modifytime` datetime NULL,
    PRIMARY KEY (`id`)
);

创建好数据库表后我们需要创建一个 pojo,在 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;

import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Bot {
    @TableId(value = "id", type = IdType.AUTO)  // 声明id为自增类型
    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 Date createtime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date modifytime;
}

然后就可以实现 mapper,在 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> {
}

2. 实现后端API

首先在 service.user 包下创建 bot 包存放与 Bot 相关的 Service 代码,然后在 service.impl.user 包下创建 bot 包存放相应的 Service 实现代码,最后在 controller.user 包下创建 bot 包存放 Controller。

我们需要实现以下四个 API:

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

service.user.bot 包下创建这四个 API 的 Service 接口:

(1)AddService

java">package com.kob.backend.service.user.bot;

import java.util.Map;

public interface AddService {
    Map<String, String> add(Map<String, String> data);
}

(2)RemoveService

java">package com.kob.backend.service.user.bot;

import java.util.Map;

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

(3)UpdateService

java">package com.kob.backend.service.user.bot;

import java.util.Map;

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

(4)GetListService

java">package com.kob.backend.service.user.bot;

import com.kob.backend.pojo.Bot;

import java.util.List;

public interface GetListService {
    List<Bot> getList();  // 根据用户信息获取Bot,用户信息存放在令牌中,因此不用传参数
}

接下来在 service.impl.user.bot 包下创建这四个 Service 接口的实现:

(1)AddServiceImpl

java">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> res = new HashMap<>();

        if (title == null || title.isEmpty()) {
            res.put("result", "The title can't be empty!");
            return res;
        }
        if (title.length() > 100) {
            res.put("result", "Title length can't exceed 100!");
            return res;
        }
        if (description == null || description.isEmpty()) {
            description = "这个用户很懒,什么也没留下~";
        }
        if (description.length() > 300) {
            res.put("result", "Description length can't exceed 300!");
            return res;
        }
        if (content == null || content.isEmpty()) {
            res.put("result", "The content can't be empty!");
            return res;
        }
        if (content.length() > 10000) {
            res.put("result", "Code length can't exceed 10000!");
            return res;
        }

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

        res.put("result", "success");
        return res;
    }
}

(2)RemoveServiceImpl

java">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();  // 需要判断要删除的Bot是不是当前登录用户的Bot

        int bot_id = Integer.parseInt(data.get("bot_id"));
        Bot bot = botMapper.selectById(bot_id);

        Map<String, String> res = new HashMap<>();

        if (bot == null) {
            res.put("result", "Bot doesn't exist!");
            return res;
        }
        if (!bot.getUserID().equals(user.getId())) {
            res.put("result", "No permission to delete the bot!");
            return res;
        }

        botMapper.deleteById(bot_id);

        res.put("result", "success");
        return null;
    }
}

(3)UpdateServiceImpl

java">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 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> res = new HashMap<>();

        if (title == null || title.isEmpty()) {
            res.put("result", "The title can't be empty!");
            return res;
        }
        if (title.length() > 100) {
            res.put("result", "Title length can't exceed 100!");
            return res;
        }
        if (description == null || description.isEmpty()) {
            description = "这个用户很懒,什么也没留下~";
        }
        if (description.length() > 300) {
            res.put("result", "Description length can't exceed 300!");
            return res;
        }
        if (content == null || content.isEmpty()) {
            res.put("result", "The content can't be empty!");
            return res;
        }
        if (content.length() > 10000) {
            res.put("result", "Code length can't exceed 10000!");
            return res;
        }

        Bot bot = botMapper.selectById(bot_id);

        if (bot == null) {
            res.put("result", "Bot doesn't exist!");
            return res;
        }
        if (!bot.getUserID().equals(user.getId())) {
            res.put("result", "No permission to update the bot!");
            return res;
        }

        Bot new_bot = new Bot(bot.getId(), user.getId(), title, description, content, bot.getRating(), bot.getCreatetime(), new Date());
        botMapper.updateById(new_bot);

        res.put("result", "success");
        return null;
    }
}

(4)GetListServiceImpl

java">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 {
    @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);
    }
}

最后在 controller.user.bot 包下创建对应的 Controller:

(1)AddController

java">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);
    }
}

(2)RemoveController

java">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);
    }
}

(3)UpdateController

java">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);
    }
}

(4)GetListController

java">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();
    }
}

http://www.niftyadmin.cn/n/5191939.html

相关文章

如何用html css js 画出曲线 或者斜线;

效果图 解题思路 将图片全部定位至中心点&#xff0c;然后x轴就变动translateX &#xff0c;y轴同理&#xff1b; 这里有两个问题 浏览器&#xff1a; 以左上角为原点0&#xff0c;0 越往下y越大 数学坐标系&#xff1a;以中心点为原点0&#xff0c;0 越往下y越小&#xff1…

【鸿蒙应用ArkTS开发系列】- 云开发入门简介

目录 概述开发流程工程概览工程模板工程结构 工程创建与配置 概述 HarmonyOS云开发是DevEco Studio新推出的功能&#xff0c;可以让您在一个项目工程中&#xff0c;使用一种语言完成端侧和云侧功能的开发。 基于AppGallery Connect Serverless构建的云侧能力&#xff0c;开发…

招聘小程序源码 人才招聘网源码

招聘小程序源码 人才招聘网源码 求职招聘小程序源码系统是一种基于微信小程序的招聘平台&#xff0c;它可以帮助企业和求职者快速、方便地进行招聘和求职操作。 该系统通常包括以下功能模块&#xff1a; 用户注册和登录&#xff1a;用户可以通过微信小程序注册和登录&#…

美国服务器:全面剖析其主要优点与潜在缺点

​  服务器是网站搭建的灵魂。信息化的今天&#xff0c;我们仍需要它来为网站和应用程序提供稳定的运行环境。而美国作为全球信息技术靠前的国家之一&#xff0c;其服务器市场备受关注。那么&#xff0c;美国服务器究竟有哪些主要优点和潜在缺点呢? 优点 数据中心基础设施&a…

数据结构与算法设计分析——常用搜索算法

目录 一、穷举搜索二、图的遍历算法&#xff08;一&#xff09;深度优先搜索&#xff08;DFS&#xff09;&#xff08;二&#xff09;广度优先搜索&#xff08;BFS&#xff09; 三、回溯法&#xff08;一&#xff09;回溯法的定义&#xff08;二&#xff09;回溯法的应用 四、分…

杭州信息安全

更轻量级的用户开销 (Lower online burden) 更灵活的通信模型 (Flexible metadata-private messaging) 一对一通信 >多对一、一对多通信 Group messaging Broadcast / anycast 元数据隐私保护技术在其他系统的推广

frp新版本frp_0.52.3设置

服务端 frps.toml cp /root/frp/frpc /usr/bin #bindPort 7000 bindPort 7000# 如果指定了“oidc”&#xff0c;将使用 OIDC 设置颁发 OIDC&#xff08;开放 ID 连接&#xff09;令牌。默认情况下&#xff0c;此值为“令牌”。auth.method “token” auth.method "…

智能配电系统解决方案

智能配电系统解决方案是一种集成了先进技术和智能化功能的配电系统&#xff0c;它能够提高电力系统的效率、可靠性和安全性。力安科技智能配电系统解决方案依托电易云-智慧电力物联网&#xff0c;具体实施的方案如下&#xff1a; 智能化设备和传感器&#xff1a;采用智能化的开…