Java 小项目开发日记 04(文章接口的开发、oss图片上传)

Java 小项目开发日记 04(文章接口的开发、oss图片上传)

项目目录

在这里插入图片描述

配置文件(pom.xml)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!--继承父工程--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.6</version></parent><groupId>com.zhong</groupId><artifactId>big-event</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>big-event</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!--web 依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--MyBatis 依赖--><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>3.0.0</version></dependency><!--MySQL 依赖--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><!--lombok 依赖--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><!--参数校验依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency><!--jwt 令牌验证--><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.4.0</version></dependency><!--单元测试依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><!--pageHelper 分页助手--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.6</version></dependency><!--阿里云oss依赖--><dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.8.0</version></dependency><dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.1</version></dependency><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency><!-- no more than 2.3.3--><dependency><groupId>org.glassfish.jaxb</groupId><artifactId>jaxb-runtime</artifactId><version>2.3.3</version></dependency></dependencies>
</project>

resources 配置

  • resources
    • application.yml
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/big_eventusername: rootpassword: 123456# 设置文件上传大小servlet:multipart:max-file-size: 10MBmax-request-size: 10MB
mybatis:configuration:map-underscore-to-camel-case: true    # 开启下划线映射alioss:   # 阿里云配置endpoint: "https://oss-cn-beijing.aliyuncs.com"    # Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。bucketName: ""  # 填写Bucket名称,例如examplebucket。access_key: ""  # 点击头像->Accesskey管理查看 秘钥access_key_secret: "" # 密码

resources 配置(动态SQL)

  • resources
    • com.zhong.mapper
      • application.yml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhong.mapper.ArticleMapper"><!--动态 SQL--><select id="findAllArticle" resultType="com.zhong.pojo.Article">select * from article<where><if test="categoryId != null">category_id = #{categoryId}</if><if test="state != null">AND state = #{state}</if>AND create_user = #{id}</where></select>
</mapper>

config

  • WebConfig
package com.zhong.config;import com.zhong.interceptors.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** @ClassName : WebConfig* @Description : Web 配置* @Author : zhx* @Date: 2024-02-28 19:30*/
@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate LoginInterceptor loginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor).excludePathPatterns("/user/login", "/user/register");}
}

controller

  • ArticleController
package com.zhong.controller;import com.zhong.pojo.Category;
import com.zhong.pojo.Result;
import com.zhong.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;import java.util.List;/*** @ClassName : CategoryController* @Description : 文章操作* @Author : zhx* @Date: 2024-02-29 19:46*/
@RestController
@RequestMapping("/category")
public class CategoryController {@Autowiredprivate CategoryService categoryService;@PostMappingpublic Result add(@RequestBody @Validated(Category.Add.class) Category category) {categoryService.add(category);return Result.success();}@GetMappingpublic Result<List<Category>> findAll() {List<Category> category = categoryService.findAll();return Result.success(category);}@GetMapping("/detail")public Result<Category> findCategoryById(@RequestHeader @Validated(Category.Update.class) Integer id) {return Result.success(categoryService.findCategoryById(id));}@PutMappingpublic Result updateCategory(@RequestBody @Validated(Category.Update.class) Category category) {categoryService.updateCategory(category);return Result.success();}@DeleteMappingpublic Result deleteCategory(@RequestHeader @Validated(Category.Update.class) Integer id){categoryService.deleteCategory(id);return Result.success();}
}
  • CategoryController
package com.zhong.controller;import com.zhong.pojo.Category;
import com.zhong.pojo.Result;
import com.zhong.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;import java.util.List;/*** @ClassName : CategoryController* @Description : 文章操作* @Author : zhx* @Date: 2024-02-29 19:46*/
@RestController
@RequestMapping("/category")
public class CategoryController {@Autowiredprivate CategoryService categoryService;@PostMappingpublic Result add(@RequestBody @Validated(Category.Add.class) Category category) {categoryService.add(category);return Result.success();}@GetMappingpublic Result<List<Category>> findAll() {List<Category> category = categoryService.findAll();return Result.success(category);}@GetMapping("/detail")public Result<Category> findCategoryById(@RequestHeader @Validated(Category.Update.class) Integer id) {return Result.success(categoryService.findCategoryById(id));}@PutMappingpublic Result updateCategory(@RequestBody @Validated(Category.Update.class) Category category) {categoryService.updateCategory(category);return Result.success();}@DeleteMappingpublic Result deleteCategory(@RequestHeader @Validated(Category.Update.class) Integer id){categoryService.deleteCategory(id);return Result.success();}
}
  • FileUploadController
package com.zhong.controller;import com.zhong.pojo.Result;
import com.zhong.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.util.UUID;/*** @ClassName : FileUploadController* @Description : 文件上传相关操作* @Author : zhx* @Date: 2024-03-01 19:45*/
@RestControllerpublic class FileUploadController {@PostMapping("/upload")public Result<String> uploadImage(MultipartFile file) throws Exception {// 获取文件原名String originalFilename = file.getOriginalFilename();// 防止重复上传文件名重复String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.indexOf("."));// 把文件储存到本地磁盘
//        file.transferTo(new File("E:\\SpringBootBase\\ProjectOne\\big-event\\src\\main\\resources\\flies\\" + fileName));String url = AliOssUtil.uploadFile(fileName, file.getInputStream());return Result.success(url);}
}
  • UserController
package com.zhong.controller;import com.zhong.pojo.Result;
import com.zhong.pojo.User;
import com.zhong.service.UserService;
import com.zhong.utils.JwtUtil;
import com.zhong.utils.Md5Util;
import com.zhong.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.Map;/*** @ClassName : UserController* @Description : 用户操作* @Author : zhx* @Date: 2024-02-27 20:40*/
@RestController
@RequestMapping("/user")
@Validated
public class UserController {@Autowiredprivate UserService userService;@PostMapping("/register")public Result register(@Pattern(regexp = "^\\S{6,16}$") String username, @Pattern(regexp = "^\\S{6,16}$") String password) {// 查询用户User user = userService.findByUserName(username);if (user == null) {// 没有被占用// 注册userService.registerUser(username, password);return Result.success();} else {// 被占用return Result.error("用户名已被占用......");}}@PostMapping("/login")public Result<String> login(@Pattern(regexp = "^\\S{2,10}$") String username, @Pattern(regexp = "^\\S{6,16}$") String password) {User user = userService.findByUserName(username);// 密码正确 登录if (user == null) {return Result.error("用户不存在......");}if (Md5Util.checkPassword(password, user.getPassword())) {  // 验证用户密码HashMap<String, Object> claims = new HashMap<>();   // 创建校验mapclaims.put("id", user.getId()); // 添加用户 IDclaims.put("username", user.getUsername()); // 添加用户名return Result.success(JwtUtil.genToken(claims));    // 返回获取到的 token}return Result.error("密码错误......");}@GetMapping("/userinfo")public Result<User> getUserInfo() {// 获取线程中的 user 对象Map<String, Object> user = ThreadLocalUtil.get();User userInfo = userService.getUserInfo((Integer) user.get("id"));return Result.success(userInfo);}@PutMapping("/update")public Result update(@RequestBody @Validated User user) {if (!userService.update(user)) {return Result.error("修改失败......");}return Result.success("修改成功!");}@PatchMapping("/updatepwd")public Result updatePassWord(@RequestBody Map<String, String> params) {String oldPwd = params.get("old_pwd");String newPwd = params.get("new_pwd");String rePwd = params.get("re_pwd");if (oldPwd.equals(newPwd) || oldPwd.equals(rePwd)) {return Result.error("修改密码与原密码相同......");}if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){return Result.error("密码不能为空......");}if (!newPwd.equals(rePwd)) {return Result.error("新密码不一致......");}if (!userService.updatePassWord(oldPwd, newPwd)){return Result.error("原密码不匹配......");}return Result.success("修改密码成功!");}
}

exception

  • GlobalExceptionHandler
package com.zhong.exception;import com.zhong.pojo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;/*** @ClassName : GlobalExceptionHandler* @Description : 全局异常处理* @Author : zhx* @Date: 2024-02-27 21:37*/
@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public Result handlerException(Exception e) {e.printStackTrace();return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败");}
}

interceptors

  • LoginInterceptor
package com.zhong.interceptors;import com.zhong.utils.JwtUtil;
import com.zhong.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;import java.util.Map;/*** @ClassName : LoginInterceptor* @Description : 登录拦截器* @Author : zhx* @Date: 2024-02-28 19:25*/
@Component
public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 获取浏览器中的 tokenString token = request.getHeader("Authorization");// 解析 tokentry {Map<String, Object> claims = JwtUtil.parseToken(token);// 把得到的数据存入 ThreadLocalThreadLocalUtil.set(claims);// 放行return true;} catch (Exception e) {response.setStatus(401);// 拦截return false;}}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// 清空 ThreadLocal 中的数据  防止内存泄漏ThreadLocalUtil.remove();}
}

mapper

  • ArticleMapper
package com.zhong.mapper;import com.zhong.pojo.Article;
import com.zhong.pojo.PageBean;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;import java.util.List;/*** @ClassName : ArticleMapper* @Description : 文章 SQL 操作* @Author : zhx* @Date: 2024-03-01 17:46*/
@Mapper
public interface ArticleMapper {@Insert("insert into article(title, content, cover_img, state, category_id, create_user, create_time, update_time) " +"VALUES (#{title}, #{content}, #{coverImg}, #{state}, #{categoryId}, #{createUser}, now(), now())")void addArticle(Article article);// 这里的 SQL 操作映射到 ArticleMapper.xml 文件中了List<Article> findAllArticle(Integer id, Integer categoryId, String state);
}
  • CategoryMapper
package com.zhong.mapper;import com.zhong.pojo.Category;
import org.apache.ibatis.annotations.*;import java.util.List;/*** @ClassName : CategoryMapper* @Description : 文章SQL* @Author : zhx* @Date: 2024-02-29 19:50*/
@Mapper
public interface CategoryMapper {@Insert("insert into category(category_name, category_alias, create_user, create_time, update_time) values (#{categoryName}, #{categoryAlias}, #{createUser} , now(), now())")void add(Category category);@Select("select * from category where create_user = #{userId}")List<Category> findAll(Integer userId);@Select("select * from category where id = #{id}")Category findCategoryById(Integer id);@Update("update category set category_name = #{categoryName}, category_alias = #{categoryAlias}, update_time = now() where id = #{id}")void updateCategory(Category category);@Delete("delete from category where id = #{id}")void deleteCategory(Integer id);
}
  • UserMapper
package com.zhong.mapper;import com.zhong.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;/*** @ClassName : UserMapper* @Description : 用户业务逻辑* @Author : zhx* @Date: 2024-02-27 20:42*/
@Mapper
public interface UserMapper {// 根据用户名查询用户@Select("select * from user where username = #{username}")User findByUserName(String username);// 添加用户@Insert("insert into user(username, password, create_time, update_time) values (#{username}, #{password}, now(), now()) ")void registerUser(String username, String password);@Select("select * from user where id = #{id}")User getUserInfo(Integer id);@Update("update user set username = #{user.username}, nickname = #{user.nickname}, email = #{user.email}, user_pic=#{user.userPic}, update_time = now() where id = #{myId};")Boolean update(User user,Integer myId);@Update("update user set password = #{newP}, update_time = now() where id= #{id} AND password = #{oldP}")boolean updatePassWord(Integer id, String oldP, String newP);
}

pojo

  • Article
package com.zhong.pojo;import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.hibernate.validator.constraints.URL;import java.time.LocalDateTime;
@Data
public class Article {private Integer id;//主键ID@NotEmpty@Pattern(regexp = "^\\S{1,12}$")private String title;//文章标题@NotEmptyprivate String content;//文章内容@NotEmpty@URLprivate String coverImg;//封面图像private String state;//发布状态 已发布|草稿@NotNullprivate Integer categoryId;//文章分类idprivate Integer createUser;//创建人IDprivate LocalDateTime createTime;//创建时间private LocalDateTime updateTime;//更新时间
}
  • Category
package com.zhong.pojo;import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.groups.Default;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDateTime;@Data
public class Category {@NotNull(groups = Update.class)private Integer id;//主键ID@NotEmptyprivate String categoryName;//分类名称@NotEmptyprivate String categoryAlias;//分类别名@JsonIgnore // 转换成 json 的时候忽略该字段private Integer createUser;//创建人ID@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime createTime;//创建时间@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime updateTime;//更新时间// Default 继承默认分组 不添加分组信息则是默认分组public interface Add extends Default {}public interface Update extends Default{}
}
  • PageBean
package com.zhong.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.List;//分页返回结果对象
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean <T>{private Long total;//总条数private List<T> items;//当前页数据集合
}
  • Result
package com.zhong.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;//统一响应结果
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Result<T> {private Integer code;//业务状态码  0-成功  1-失败private String message;//提示信息private T data;//响应数据//快速返回操作成功响应结果(带响应数据)public static <E> Result<E> success(E data) {return new Result<>(0, "操作成功", data);}//快速返回操作成功响应结果public static Result success() {return new Result(0, "操作成功", null);}public static Result error(String message) {return new Result(1, message, null);}
}
  • User
package com.zhong.pojo;import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.hibernate.validator.constraints.URL;import java.time.LocalDateTime;
@Data
@NoArgsConstructor
public class User {@NonNullprivate Integer id;//主键ID@NotEmpty@Pattern(regexp = "^\\S{2,10}$")private String username;//用户名@JsonIgnore // 转换成 json 的时候忽略该字段private String password;//密码@NotEmpty@Pattern(regexp = "\\S{1,12}$")private String nickname;//昵称@NotEmpty@Emailprivate String email;//邮箱@URLprivate String userPic;//用户头像地址@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime createTime;//创建时间@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private LocalDateTime updateTime;//更新时间
}

service

  • impl
    • ArticleServiceImpl
package com.zhong.service.impl;import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhong.mapper.ArticleMapper;
import com.zhong.pojo.Article;
import com.zhong.pojo.PageBean;
import com.zhong.service.ArticleService;
import com.zhong.utils.GetNowLoginIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @ClassName : ArticleServiceImpl* @Description : 文章接口实现* @Author : zhx* @Date: 2024-03-01 17:46*/
@Service
public class ArticleServiceImpl implements ArticleService {@Autowiredprivate ArticleMapper articleMapper;@Overridepublic void addArticle(Article article) {// 设置发布人的idarticle.setCreateUser(GetNowLoginIdUtil.getID());articleMapper.addArticle(article);}@Overridepublic PageBean<Article> findAllArticle(Integer pageNum, Integer pageSize, Integer categoryId, String state) {// 创建 PageBean 对象 存储分页数据PageBean<Article> pb = new PageBean<>();// 开启分页查询PageHelper.startPage(pageNum, pageSize);// (Page<Article>) 强转: 当使用 PageHelper 分页查询后,会帮我们返回总记录条数和当前页数据// 调用 mapperPage<Article> pg = (Page<Article>) articleMapper.findAllArticle(GetNowLoginIdUtil.getID(), categoryId, state);// 将数据存入 PageBeanpb.setTotal(pg.getTotal());pb.setItems(pg.getResult());return pb;}
}
  • impl
    • CategoryServiceImpl
package com.zhong.service.impl;import com.zhong.mapper.CategoryMapper;
import com.zhong.pojo.Category;
import com.zhong.service.CategoryService;
import com.zhong.utils.GetNowLoginIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;/*** @ClassName : CategoryServiceImpl* @Description : 文章接口实现类* @Author : zhx* @Date: 2024-02-29 19:48*/
@Service
public class CategoryServiceImpl implements CategoryService {@Autowiredprivate CategoryMapper categoryMapper;@Overridepublic void add(Category category) {Integer id = GetNowLoginIdUtil.getID();category.setCreateUser(id);categoryMapper.add(category);}@Overridepublic List<Category> findAll() {Integer id = GetNowLoginIdUtil.getID();return categoryMapper.findAll(id);}@Overridepublic Category findCategoryById(Integer id) {return categoryMapper.findCategoryById(id);}@Overridepublic void updateCategory(Category category) {categoryMapper.updateCategory(category);}@Overridepublic void deleteCategory(Integer id) {categoryMapper.deleteCategory(id);}
}
  • impl
    • UserServiceImpl
package com.zhong.service.impl;import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhong.mapper.UserMapper;
import com.zhong.pojo.User;
import com.zhong.service.UserService;
import com.zhong.utils.JwtUtil;
import com.zhong.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Map;/*** @ClassName : UserServiceImpl* @Description : 用户接口实现类* @Author : zhx* @Date: 2024-02-27 20:41*/
@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic User findByUserName(String username) {return userMapper.findByUserName(username);}@Overridepublic void registerUser(String username, String password) {// 加密String md5String = Md5Util.getMD5String(password);// 添加userMapper.registerUser(username, md5String);}@Overridepublic User getUserInfo(Integer id) {return userMapper.getUserInfo(id);}@Overridepublic Boolean update(User user) {return userMapper.update(user);}}
  • ArticleService
package com.zhong.service;import com.zhong.pojo.Article;
import com.zhong.pojo.PageBean;import java.util.List;/*** @ClassName : ArticleService* @Description : 文章接口* @Author : zhx* @Date: 2024-03-01 17:45*/
public interface ArticleService {void addArticle(Article article);PageBean<Article> findAllArticle(Integer pageNum, Integer pageSize, Integer categoryId, String state);
}
  • CategoryService
package com.zhong.service;import com.zhong.pojo.Category;import java.util.List;/*** @ClassName : CategoryService* @Description : 文章接口* @Author : zhx* @Date: 2024-02-29 19:47*/
public interface CategoryService {// 添加分类void add(Category category);List<Category> findAll();Category findCategoryById(Integer id);void updateCategory(Category category);void deleteCategory(Integer id);
}
  • UserService
package com.zhong.service;import com.zhong.pojo.User;/*** @ClassName : UserService* @Description : 用户接口* @Author : zhx* @Date: 2024-02-27 20:40*/
public interface UserService {// 根据用户名查询用户User findByUserName(String username);// 注册用户void registerUser(String username, String password);User getUserInfo(Integer id);Boolean update(User user);
}

utils

  • AliOssUtil
package com.zhong.utils;import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;import java.io.InputStream;
/*** @ClassName : AliOssUtil* @Description : 阿里云上传服务* @Author : zhx* @Date: 2024-03-1 20:29*/
@Component
public class AliOssUtil {private static String ENDPOINT;@Value("${alioss.endpoint}")public void setENDPOINT(String endpoint){ENDPOINT = endpoint;}private static String ACCESS_KEY;@Value("${alioss.access_key}")public void setAccessKey(String accessKey){ACCESS_KEY = accessKey;}private static String ACCESS_KEY_SECRET;@Value("${alioss.access_key_secret}")public void setAccessKeySecret(String accessKeySecret){ACCESS_KEY_SECRET = accessKeySecret;}private static String BUCKETNAME;@Value("${alioss.bucketName}")public void setBUCKETNAME(String bucketName){BUCKETNAME = bucketName;}public static String uploadFile(String objectName, InputStream inputStream) {String url = "";// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);try {// 创建PutObjectRequest对象。PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName, inputStream);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。// ObjectMetadata metadata = new ObjectMetadata();// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());// metadata.setObjectAcl(CannedAccessControlList.Private);// putObjectRequest.setMetadata(metadata);// 上传文件。PutObjectResult result = ossClient.putObject(putObjectRequest);url = "https://" + BUCKETNAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + objectName;} catch (OSSException oe) {System.out.println("Caught an OSSException, which means your request made it to OSS, "+ "but was rejected with an error response for some reason.");System.out.println("Error Message:" + oe.getErrorMessage());System.out.println("Error Code:" + oe.getErrorCode());System.out.println("Request ID:" + oe.getRequestId());System.out.println("Host ID:" + oe.getHostId());} catch (ClientException ce) {System.out.println("Caught an ClientException, which means the client encountered "+ "a serious internal problem while trying to communicate with OSS, "+ "such as not being able to access the network.");System.out.println("Error Message:" + ce.getMessage());} finally {if (ossClient != null) {ossClient.shutdown();}}return url;}
}
  • GetNowLoginIdUtil
package com.zhong.utils;import java.util.Map;/*** @ClassName : GetNowLoginId* @Description : 获取当前用户登录的 id* @Author : zhx* @Date: 2024-02-29 20:32*/
public class GetNowLoginIdUtil {public static Integer getID(){Map<String, Object> claims = ThreadLocalUtil.get();return (Integer) claims.get("id");}
}
  • JwtUtil
package com.zhong.utils;import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;import java.util.Date;
import java.util.Map;public class JwtUtil {private static final String KEY = "zhong";//接收业务数据,生成token并返回public static String genToken(Map<String, Object> claims) {return JWT.create().withClaim("claims", claims).withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12)).sign(Algorithm.HMAC256(KEY));}//接收token,验证token,并返回业务数据public static Map<String, Object> parseToken(String token) {return JWT.require(Algorithm.HMAC256(KEY)).build().verify(token).getClaim("claims").asMap();}}
  • Md5Util
package com.zhong.utils;import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;public class Md5Util {/*** 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合*/protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};protected static MessageDigest messagedigest = null;static {try {messagedigest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException nsaex) {System.err.println(Md5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");nsaex.printStackTrace();}}/*** 生成字符串的md5校验值** @param s* @return*/public static String getMD5String(String s) {return getMD5String(s.getBytes());}/*** 判断字符串的md5校验码是否与一个已知的md5码相匹配** @param password  要校验的字符串* @param md5PwdStr 已知的md5校验码* @return*/public static boolean checkPassword(String password, String md5PwdStr) {String s = getMD5String(password);return s.equals(md5PwdStr);}public static String getMD5String(byte[] bytes) {messagedigest.update(bytes);return bufferToHex(messagedigest.digest());}private static String bufferToHex(byte bytes[]) {return bufferToHex(bytes, 0, bytes.length);}private static String bufferToHex(byte bytes[], int m, int n) {StringBuffer stringbuffer = new StringBuffer(2 * n);int k = m + n;for (int l = m; l < k; l++) {appendHexPair(bytes[l], stringbuffer);}return stringbuffer.toString();}private static void appendHexPair(byte bt, StringBuffer stringbuffer) {char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>>// 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换stringbuffer.append(c0);stringbuffer.append(c1);}
}
  • ThreadLocalUtil
package com.zhong.utils;/*** ThreadLocal 工具类*/
@SuppressWarnings("all")
public class ThreadLocalUtil {//提供ThreadLocal对象,private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();//根据键获取值public static <T> T get(){return (T) THREAD_LOCAL.get();}//存储键值对public static void set(Object value){THREAD_LOCAL.set(value);}//清除ThreadLocal 防止内存泄漏public static void remove(){THREAD_LOCAL.remove();}
}

BigEventApplication

package com.zhong;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class BigEventApplication {public static void main(String[] args) {SpringApplication.run(BigEventApplication.class, args);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/715029.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

机器学习:集成学习(Python)

一、Adaboost算法 1.1 Adaboost分类算法 adaboost_discrete_c.py import numpy as np import copy from ch4.decision_tree_C import DecisionTreeClassifierclass AdaBoostClassifier:"""adaboost分类算法&#xff1a;既可以做二分类、也可以做多分类&#…

uniapp的h5端在线预览文件

步骤如下&#xff1a; 1、下载需要准备的工具文件包 2、将其解压到/static/pdf文件夹下,如图&#xff1a; 3、创建在线查看文件的页面&#xff1a; <template><view><web-view :src"path"></web-view></view> </template>&l…

JavaScript练手小技巧:一文看懂<script>标签的 ansyc 和 defer

<script>标签的 ansyc 和 defer 属性。只对外部加载 JS 文件有效。 <script src"js/app.js" async></script> <script src"js/app.js" defer></script> 普通加载 js&#xff08;同步加载&#xff09;&#xff1a;会打断 …

Vue3 isProxy,isReactive,isReadonly 三者解析

1、isProxy 作用&#xff1a;判断当前数据是否为代理数据。 注意&#xff1a;它只对通过 reactive&#xff0c;readonly&#xff0c;shallowReactive&#xff0c;shallowReadonly 这四个方法包裹的数据返回true&#xff0c;对于 ref 以及通过 new Proxy 代理的数据返回都是fal…

ChatGPT科研与AI绘图及论文高效写作教程

原文链接&#xff1a;ChatGPT科研与AI绘图及论文高效写作教程 2023年随着OpenAI开发者大会的召开&#xff0c;最重磅更新当属GPTs&#xff0c;多模态API&#xff0c;未来自定义专属的GPT。微软创始人比尔盖茨称ChatGPT的出现有着重大历史意义&#xff0c;不亚于互联网和个人电…

HPE ProLiant MicroServer Gen8更换坏硬盘(RAID 1+0)

HPE ProLiant MicroServer Gen8今天硬盘告警&#xff0c;坏了一块硬盘&#xff08;估计还是由于上次突然断电导致的&#xff09;&#xff0c;关机&#xff0c;拆下坏硬盘&#xff0c;更换新硬盘&#xff0c;开机后按了一次F1键&#xff0c;系统继续启动并正常使用&#xff0c;同…

高性能MySQL 第4版

第一章MySQL架构 MySQL提供了多种锁的颗粒度&#xff0c;每种MySQL存储引擎都可以实现自己的锁策略和锁力度。 行级锁是在存储引擎而不是在服务器中实现的。 隔离界别 READ UNCOMMITTED - 脏读 在事务中可以可以查看到其他事务中还没有提交的修改。实际中很少用。 READ C…

Linux网络编程——socket 通信基础

Linux网络编程——socket 通信基础 1. socket 介绍2. 字节序2.1 简介2.2 字节序举例2.3 字节序转换函数 3. socket 地址3.1 通用 socket 地址3.2 专用 socket 地址 4. IP地址转换&#xff08;字符串ip -> 整数&#xff0c;主机、网络字节序的转换 &#xff09;5. TCP 通信流…

算法------(13)KMP

例题&#xff1a;&#xff08;1&#xff09;AcWing 831. KMP字符串 。。其实写完也不太理解。。随便写点吧 KMP就是求next数组和运用next的数组的过程。相比传统匹配模式一次更新一单位距离的慢速方法&#xff0c;next数组可以让下表字符串一次更新n - next【n】个距离&#x…

Java读取文件

读取文件为String 、访问链接直接跳转html 环境&#xff1a;SpringMVC 、前端jsp InputStreamReader FileInputStream fileInputStream new FileInputStream(formatFile.getHtmlpath());InputStreamReader reader new InputStreamReader(fileInputStream, StandardCharsets…

【EAI 026】RoboGen: 通过自动数据生成管线实现机器人技能学习

Paper Card 论文标题&#xff1a;RoboGen: Towards Unleashing Infinite Data for Automated Robot Learning via Generative Simulation 论文作者&#xff1a;Yufei Wang, Zhou Xian, Feng Chen, Tsun-Hsuan Wang, Yian Wang, Zackory Erickson, David Held, Chuang Gan 作者单…

C++:菱形继承问题

目录 1、什么是菱形继承 2、虚拟继承 3、一些常见问题 1. 什么是菱形继承&#xff1f;菱形继承的问题是什么&#xff1f; 2. 什么是菱形虚拟继承&#xff1f;如何解决数据冗余和二义性的 3. 继承和组合的区别&#xff1f;什么时候用继承&#xff1f;什么时候用组合&#…

Qt 自定义长条进度条(类似播放器进度条)

1.运行界面 2.步骤 其实很简单。 2.1绘制底图圆角矩形 2.2绘制播放进度圆角矩形 参考&#xff1a;painter绘图 3.源码 #pragma once#include <QWidget> #include <QLabel> #include <QHBoxLayout> #include <QMouseEvent> #include <QDebug&g…

Slicer学习笔记(六十五) 3DSlicer的医学图像数据增强扩展模块

1. 医学图像数据增强扩展模块 基于3D Slicer5.1.0 编写了一个测试医学图像的数据增强测试扩展模块。 扩展模块名&#xff1a;DataAugementation 项目地址&#xff1a;DataAugmentation 下载该项目后&#xff0c;可以将该扩展模块添加到3D Slicer的扩展中。 关于如何给3DSlicer…

微信自动回复,基于python

#!/usr/bin/python3 # -*- coding: utf-8 -*-import numpy as np import pandas as pd from uiautomation import WindowControl import csvwx WindowControl(Name微信,searchDepth1 ) # 切换窗口 wx.ListControl() wx.SwitchToThisWindow() # 寻找会话控件绑定 hw wx.…

LaTeX-设置表格大小

文章目录 LaTeX-设置表格大小1.创建表格2.设置表格的宽度2.1控制表格每一列的宽度2.2控制整个表格的宽度 3.设置表格的外观4.LaTeX绘制三线表 LaTeX-设置表格大小 本文介绍了LaTeX如何设置表格的大小、改变表格的外观以及如何绘制三线表。 1.创建表格 在LaTeX中创建表很耗时…

【前端素材】推荐优质后台管理系统网页my-Task平台模板(附源码)

一、需求分析 1、系统定义 后台管理系统是一种用于管理网站、应用程序或系统的工具&#xff0c;通常由管理员使用。后台管理系统是一种用于管理和控制网站、应用程序或系统的管理界面。它通常被设计用来让网站或应用程序的管理员或运营人员管理内容、用户、数据以及其他相关功…

2023年NOC大赛软件创意编程(学而思)赛道图形化小低高组决赛试题

2023NOC 决赛-小低组 每个小朋友从小会有梦寐以求的愿望,或是拥有孙悟空七十二变的能 力,或是像神笔马良一样想要什么画什么,或是成为人见人爱的国宝 大熊猫,或是变身全能机器人……今天,你可以用编程实现自己愿望! 【题目要求】 请以“假如我是_____”为题,自选主…

Sentinel实战(待完善)

目录 服务雪崩 什么是服务雪崩 服务不可用原因 解决方案 技术选型对比 Sentinel 介绍 优点 核心概念 资源 规则 代码实战 API实现 SentinelResource注解实现 Sentinel控制台 启动控制台服务 java应用接入控制台 微服务接入Sentinel 服务雪崩 什么是服务雪崩…

DETR详解

1. 动机 传统的目标检测任务需要大量的人工先验知识&#xff0c;例如预定义的先验anchor&#xff0c;NMS后处理策略等。这些人工先验知识引入了很多人为因素&#xff0c;且较难处理。如果能够端到端到直接生成目标检测结果&#xff0c;将会使问题变得很优雅。 2. 主要贡献 提…