【Java闭关修炼】SpringBoot项目-贪吃蛇对战小游戏-创建个人中心页面(上)

本文主要是介绍【Java闭关修炼】SpringBoot项目-贪吃蛇对战小游戏-创建个人中心页面(上),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【Java闭关修炼】SpringBoot项目-贪吃蛇对战小游戏-创建个人中心页面(上)

    • 创建一个user表
    • 创建pojo.bot
    • 实现后端API
      • AddService接口
      • AddService接口实现
      • AddController
      • 添加bot记录的前端页面
      • RemoveServiceImpl
      • RemoveController
      • 前端删除Bot记录测试
      • UpdateServiceImpl
      • UpdateController
      • Update前端测试
      • GetListImpl
      • GetListController
      • 前端页面测试

创建一个user表

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lzGoccPt-1679971611476)(../images/c939cbdfeb83e820a543223dc335b7269138908472d45f7a2fb22e64e359019c.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XpDj1xeK-1679971611478)(../images/3ee716150da0fada3cc78c1ab2322c2fc92acb9f51ad2f11c0f834c4ed15462c.png)]

创建pojo.bot

package com.kob.backedn2.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
@AllArgsConstructor
@NoArgsConstructor
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;
}

实现后端API

在这里插入图片描述

AddService接口

package com.kob.backedn2.service.user.bot;import java.util.Map;// 添加bot接口
public interface AddService {public Map<String,String> add(Map<String,String> data);
}

AddService接口实现

package com.kob.backedn2.service.impl.user.bot;import com.kob.backedn2.mapper.BotMapper;
import com.kob.backedn2.pojo.Bot;
import com.kob.backedn2.pojo.User;
import com.kob.backedn2.service.impl.utils.UserDetailsImpl;
import com.kob.backedn2.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 {// 将接口注入进来@Autowiredprivate BotMapper botMapper;// 使用Mapper操作数据库@Overridepublic Map<String, String> add(Map<String, String> data) {// 从token中获取用户UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();UserDetailsImpl loginUser = (UserDetailsImpl) authenticationToken.getPrincipal();User user = loginUser.getUser();// 根据key获取map中的数据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 == null || description.length() == 0){description = "这个用户很懒,什么也没留下";}if(description != null && 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对象Date now = new Date();Bot bot = new Bot(null,user.getId(),title,description,content,1500,now,now);// 将Bot对象添加到数据库中botMapper.insert(bot);map.put("error_message","success");return map;}
}

AddController

package com.kob.backedn2.controller.user.bot;import com.kob.backedn2.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 {// 将实现的service接口进行注入@Autowiredprivate AddService addService;// 用户访问该url路径 获取资源@PostMapping("/user/bot/add/")public Map<String,String> add(@RequestParam Map<String,String> data){// 调用service 插入数据return addService.add(data);}
}

添加bot记录的前端页面

点击我的bot页面 自动创建一个bot

<template><ContentField>我的Bot</ContentField>
</template><script>
import ContentField from '../../../components/ContentField.vue'
import $ from 'jquery'
import { useStore} from 'vuex';export default {components: {ContentField},setup(){const store = useStore();// 获取全局资源$.ajax({url:"http://127.0.0.1:3000/user/bot/add/",type:"POST",data:{title:"Bot的标题",description:"Bot的描述",content:"Bot的代码",},headers:{// 验证Authorization:"Bearer " + store.state.user.token,},success(resp){//  打印是否成功的消息console.log(resp);},error(resp){console.log(resp);}})}
}
</script><style scoped>
</style>

RemoveServiceImpl

package com.kob.backedn2.service.impl.user.bot;import com.kob.backedn2.mapper.BotMapper;
import com.kob.backedn2.pojo.Bot;
import com.kob.backedn2.pojo.User;
import com.kob.backedn2.service.impl.utils.UserDetailsImpl;
import com.kob.backedn2.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 {@Autowiredprivate BotMapper botMapper;@Overridepublic 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的id// 获取botBot 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_message","success");return null;}
}

RemoveController

package com.kob.backedn2.controller.user.bot;import com.kob.backedn2.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 {@Autowiredprivate RemoveService removeService;@PostMapping("/user/bot/remove")public Map<String,String> remove(@RequestParam Map<String,String> data){return removeService.remove(data);//调用service接口的方法}}

前端删除Bot记录测试

<template><ContentField>我的Bot</ContentField>
</template><script>
import ContentField from '../../../components/ContentField.vue'
import $ from 'jquery'
import { useStore} from 'vuex';export default {components: {ContentField},setup(){const store = useStore();// 获取全局资源// $.ajax({//     url:"http://127.0.0.1:3000/user/bot/add/",//     type:"POST",//     data:{//         title:"Bot的标题",//         description:"Bot的描述",//         content:"Bot的代码",//     },//     headers://     {//         // 验证//         Authorization:"Bearer " + store.state.user.token,//     },//     success(resp){//         //  打印是否成功的消息//         console.log(resp);//     },//     error(resp){//         console.log(resp);//     }// })$.ajax({url:"http://127.0.0.1:3000/user/bot/remove/",type:"POST",data:{// 删除bot_id 为2 的数据库Bot记录bot_id:2,},headers:{// 验证Authorization:"Bearer " + store.state.user.token,},success(resp){//  打印是否成功的消息console.log(resp);},error(resp){console.log(resp);}})}
}
</script><style scoped>
</style>

UpdateServiceImpl

package com.kob.backedn2.service.impl.user.bot;import com.kob.backedn2.mapper.BotMapper;
import com.kob.backedn2.pojo.Bot;
import com.kob.backedn2.pojo.User;
import com.kob.backedn2.service.impl.utils.UserDetailsImpl;
import com.kob.backedn2.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 javax.jws.soap.SOAPBinding;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;@Service
public class UpdateServiceImpl implements UpdateService {@Autowiredprivate BotMapper botMapper;@Overridepublic Map<String, String> update(Map<String, String> data) {// 现根据token知道自己是谁 获取userUsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();UserDetailsImpl loginUser = (UserDetailsImpl) usernamePasswordAuthenticationToken.getPrincipal();User user = loginUser.getUser();// 然后获取前端返回的数据  首先根据data中的bot_id 获取idint bot_id = Integer.parseInt(data.get("bot_id"));// 获取的是字符串  然后解析成int数据// 从data数据中获取title description  content三个信息  填充到新的Bot记录 然后使用Mapper接口 插入到数据库String title = data.get("title");String description = data.get("description");String content = data.get("content");Map<String,String> map = new HashMap<>();// 根据前端解析出来的bot_id  使用botMapper接口 查询数据库 返回一个bot记录Bot bot = botMapper.selectById(bot_id);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 == null || description.length() == 0){description = "这个用户很懒,什么也没留下";}if(description != null && 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;}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());// 调用接口 更新BotbotMapper.updateById(new_bot);map.put("error_message","success");return map;}
}

UpdateController

package com.kob.backedn2.controller.user.bot;import com.kob.backedn2.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 {// 注入实现的接口 然后调用实现的接口板中的方法@Autowiredprivate UpdateService updateService;// 将请求获取的data容器 作为参数 传入service接口中@PostMapping("/user/bot/update/")public Map<String,String> update(@RequestParam Map<String,String> data){return updateService.update(data);}
}

Update前端测试

<template><ContentField>我的Bot</ContentField>
</template><script>
import ContentField from '../../../components/ContentField.vue'
import $ from 'jquery'
import { useStore} from 'vuex';export default {components: {ContentField},setup(){const store = useStore();// 获取全局资源// $.ajax({//     url:"http://127.0.0.1:3000/user/bot/add/",//     type:"POST",//     data:{//         title:"Bot的标题",//         description:"Bot的描述",//         content:"Bot的代码",//     },//     headers://     {//         // 验证//         Authorization:"Bearer " + store.state.user.token,//     },//     success(resp){//         //  打印是否成功的消息//         console.log(resp);//     },//     error(resp){//         console.log(resp);//     }// })// $.ajax({//     url:"http://127.0.0.1:3000/user/bot/remove/",//     type:"POST",//     data:{//         // 删除bot_id 为1 的数据库Bot记录//         bot_id:1,//     },//     headers://     {//         // 验证//         Authorization:"Bearer " + store.state.user.token,//     },//     success(resp){//         //  打印是否成功的消息//         console.log(resp);//     },//     error(resp){//         console.log(resp);//     }// })$.ajax({url:"http://127.0.0.1:3000/user/bot/update/",type:"POST",data:{// 删除bot_id 为1 的数据库Bot记录bot_id:3,title:"更新的标题",description:"更新的描述",content:"更新的代码",},headers:{// 验证Authorization:"Bearer " + store.state.user.token,},success(resp){//  打印是否成功的消息console.log(resp);},error(resp){console.log(resp);}})}
}
</script><style scoped>
</style>

GetListImpl

package com.kob.backedn2.service.impl.user.bot;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kob.backedn2.mapper.BotMapper;
import com.kob.backedn2.pojo.Bot;
import com.kob.backedn2.pojo.User;
import com.kob.backedn2.service.impl.utils.UserDetailsImpl;
import com.kob.backedn2.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 {@Autowiredprivate BotMapper botMapper;// 注入数据库查询接口@Overridepublic 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);}
}

GetListController

package com.kob.backedn2.controller.user.bot;import com.kob.backedn2.pojo.Bot;
import com.kob.backedn2.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 {@Autowiredprivate GetListService getListService;@GetMapping("/user/bot/getlist/")public List<Bot> getList(){return getListService.getList();}}

前端页面测试

<template><ContentField>我的Bot</ContentField>
</template><script>
import ContentField from '../../../components/ContentField.vue'
import $ from 'jquery'
import { useStore} from 'vuex';export default {components: {ContentField},setup(){const store = useStore();// 获取全局资源// $.ajax({//     url:"http://127.0.0.1:3000/user/bot/add/",//     type:"POST",//     data:{//         title:"Bot的标题",//         description:"Bot的描述",//         content:"Bot的代码",//     },//     headers://     {//         // 验证//         Authorization:"Bearer " + store.state.user.token,//     },//     success(resp){//         //  打印是否成功的消息//         console.log(resp);//     },//     error(resp){//         console.log(resp);//     }// })// $.ajax({//     url:"http://127.0.0.1:3000/user/bot/remove/",//     type:"POST",//     data:{//         // 删除bot_id 为1 的数据库Bot记录//         bot_id:1,//     },//     headers://     {//         // 验证//         Authorization:"Bearer " + store.state.user.token,//     },//     success(resp){//         //  打印是否成功的消息//         console.log(resp);//     },//     error(resp){//         console.log(resp);//     }// })// $.ajax({//     url:"http://127.0.0.1:3000/user/bot/update/",//     type:"POST",//     data:{//         // 删除bot_id 为1 的数据库Bot记录//         bot_id:3,//         title:"更新的标题",//         description:"更新的描述",//         content:"更新的代码",//     },//     headers://     {//         // 验证//         Authorization:"Bearer " + store.state.user.token,//     },//     success(resp){//         //  打印是否成功的消息//         console.log(resp);//     },//     error(resp){//         console.log(resp);//     }// })$.ajax({url:"http://127.0.0.1:3000/user/bot/getlist/",type:"get",headers:{// 验证Authorization:"Bearer " + store.state.user.token,},success(resp){//  打印是否成功的消息console.log(resp);},error(resp){console.log(resp);}})}
}
</script><style scoped>
</style>

这篇关于【Java闭关修炼】SpringBoot项目-贪吃蛇对战小游戏-创建个人中心页面(上)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/376417

相关文章

ESP32 esp-idf esp-adf环境安装及.a库创建与编译

简介 ESP32 功能丰富的 Wi-Fi & 蓝牙 MCU, 适用于多样的物联网应用。使用freertos操作系统。 ESP-IDF 官方物联网开发框架。 ESP-ADF 官方音频开发框架。 文档参照 https://espressif-docs.readthedocs-hosted.com/projects/esp-adf/zh-cn/latest/get-started/index

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

用Microsoft.Extensions.Hosting 管理WPF项目.

首先引入必要的包: <ItemGroup><PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" /><PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" /><PackageReference Include="Serilog

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001