前言
最近有了想重构项目的想法,于是就把以前写的屎山重新写一遍
发现之前写的题解也略显幼稚,于是在这里更新一个船新版本的,更适合小白宝宝体质的题解
旧题解(黑历史) 毕竟也是当初自己小白的时候写的不忍删掉QAQ,留下自己曾经爬行的痕迹好像也挺有乐趣的((lll¬ω¬)
正文
在数据库中新加表bot
表中包含列:
id: int
:非空、自动增加、唯一、主键user_id: int
:非空- 注意:在
pojo
中需要定义成userId
,在queryWrappe
r中的名称仍然为user_id
title: varchar(100)
description: varchar(300)
content:varchar(10000)
rating: int:
默认值为1500create_time: datetime
pojo
中定义日期格式的注解:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
modify_time: datetime
pojo
中定义日期格式的注解:@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
创建Bot的pojo
层
pojo.Bot.java
package com.gameforces.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(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 Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date modifyTime;
}
创建mapper
层
mapper.BotMapper.java
package com.gameforces.backend.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.gameforces.backend.pojo.Bot;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface BotMapper extends BaseMapper<Bot> {
}
实现后端API
对Bot
表的CRUD
/api/user/bot/add/
:创建一个Bot
/api/user/bot/remove/
:删除一个Bot
/api/user/bot/update/
:修改一个Bot
/api/user/bot/getlist/
:查询Bot
列表
编写service
层接口
service.user.bot.AddService.java
import java.util.Map;
public interface RemoveService {
Map<String, String> remove(Map<String, String> data);
}
service.user.bot.RemoveService.java
import java.util.Map;
public interface RemoveService {
Map<String, String> remove(Map<String, String> data);
}
service.user.bot.UpdateService.java
import java.util.Map;
public interface UpdateService {
Map<String, String> update(Map<String, String> data);
}
service.user.GetListService.java
import com.gameforces.backend.pojo.Bot;
import java.util.List;
public interface GetListService {
List<Bot> getList();
}
实现service
层接口功能
实现Add
创建功能
service.impl.user.bot.AddServiceImpl.java
package com.gameforces.backend.service.impl.user.bot;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gameforces.backend.mapper.BotMapper;
import com.gameforces.backend.pojo.Bot;
import com.gameforces.backend.pojo.User;
import com.gameforces.backend.service.impl.utils.UserDetailsImpl;
import com.gameforces.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("message", "标题不能为空");
return map;
}
if (title.length() > 100) {
map.put("message", "标题长度不能超过100");
return map;
}
if (description == null || description.length() == 0) {
description = "这个用户很懒,什么都没有留下~~";
}
if (description.length() > 1000) {
map.put("message", "描述不能超过1000个字");
return map;
}
if (content == null || content.length() == 0) {
map.put("message", "代码不能为空");
return map;
}
if (content.length() > 10000) {
map.put("message", "代码长度不能超过10000");
return map;
}
QueryWrapper<Bot> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", user.getId());
if (botMapper.selectCount(queryWrapper) > 10) {
map.put("message", "bot数量不能超过10个");
return map;
}
Date now = new Date();
Bot bot = new Bot(null, user.getId(), title, description, content, 1200, now, now);
botMapper.insert(bot);
map.put("message", "success");
return map;
}
}
实现Remove
删除功能
service.impl.user.bot.RemoveServiceImpl.java
@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("message", "Bot doesn't exist!");
return map;
}
if (!bot.getUserId().equals(user.getId())) {
map.put("message", "No permission to delete the bot!");
return map;
}
botMapper.deleteById(bot_id);
map.put("message", "success");
return map;
}
}
实现Update
更新功能
service.impl.user.bot.UpdateServiceImpl.java
@Service
public class UpdateServiceImpl implements UpdateService {
@Autowired
private BotMapper botMapper;
@Autowired
private UserMapper userMapper;
@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("message", "The title can't be empty!");
return map;
}
if (title.length() > 100) {
map.put("message", "the length of title can't exceed 100!");
return map;
}
if (description == null || description.length() == 0) {
description = "这个用户很懒,什么都没有留下~~";
}
if (description.length() > 1000) {
map.put("message", "the length of description can't exceed 1000!");
return map;
}
if (content == null || content.length() == 0) {
map.put("message", "The code can't be empty!");
return map;
}
if (content.length() > 10000) {
map.put("message", "The length of code can't exceed 10000!");
return map;
}
Bot bot = botMapper.selectById(bot_id);
if (bot == null) {
map.put("message", "Bot doesn't exist!");
return map;
}
if (!bot.getUserId().equals(user.getId())) {
map.put("message", "No permission to update the 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);
QueryWrapper<Bot> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_id", user.getId());
List<Bot> bots = botMapper.selectList(queryWrapper);
int avg_rating = 0;
for (Bot item : bots)
avg_rating += item.getRating();
avg_rating /= bots.size();
User new_user = new User(
user.getId(),
user.getUsername(),
user.getPassword(),
avg_rating,
user.getPhoto()
);
userMapper.updateById(new_user);
map.put("message", "success");
return map;
}
}
实现GetList
查询自己的Bot
信息功能
service.impl.user.bot.GetListServiceImpl.java
@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()); //注意这里user_id是与数据库里面的列名对应的,而pojo层要用驼峰命名法userId
return botMapper.selectList(queryWrapper);
}
}
编写Controller
层API
实现添加一个Bot
的后端API
controller.user.bot.AddController.java
package com.gameforces.backend.controller.user.bot;
import com.gameforces.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("/api/user/bot/add/")
public Map<String, String> work(@RequestParam Map<String, String> data) {
return addService.add(data);
}
}
实现删除一个Bot
的后端API
controller.user.bot.RemoveController.java
import com.gameforces.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("/api/user/bot/remove/")
public Map<String, String> remove(@RequestParam Map<String, String> data) {
return removeService.remove(data);
}
}
实现更新一个Bot
信息的后端API
controller.user.bot.UpdateController.java
@RestController
public class UpdateController {
@Autowired
private UpdateService updateService;
@PostMapping("/api/bot/update/")
public Map<String, String> update(@RequestParam Map<String, String> data) {
return updateService.update(data);
}
}
实现查询Bot
列表的后端API
controller.user.bot.GetListController.java
@RestController
public class GetListController {
@Autowired
private GetListService getListService;
@GetMapping("/api/user/bot/getlist/")
public List<Bot> getList() {
return getListService.getList();
}
}