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.Driver
    url: jdbc:mysql://localhost:3306/big_event
    username: root
    password: 123456
  # 设置文件上传大小
  servlet:
    multipart:
      max-file-size: 10MB
      max-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 mapper
        PUBLIC "-//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 {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public 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 {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    @GetMapping
    public 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));
    }

    @PutMapping
    public Result updateCategory(@RequestBody @Validated(Category.Update.class) Category category) {
        categoryService.updateCategory(category);
        return Result.success();
    }

    @DeleteMapping
    public 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 {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    @GetMapping
    public 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));
    }

    @PutMapping
    public Result updateCategory(@RequestBody @Validated(Category.Update.class) Category category) {
        categoryService.updateCategory(category);
        return Result.success();
    }

    @DeleteMapping
    public 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
 */
@RestController

public 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 {

    @Autowired
    private 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<>();   // 创建校验map
            claims.put("id", user.getId()); // 添加用户 ID
            claims.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 {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取浏览器中的 token
        String token = request.getHeader("Authorization");
        // 解析 token
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 把得到的数据存入 ThreadLocal
            ThreadLocalUtil.set(claims);
            // 放行
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            // 拦截
            return false;
        }
    }

    @Override
    public 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;//文章标题

    @NotEmpty
    private String content;//文章内容

    @NotEmpty
    @URL
    private String coverImg;//封面图像

    private String state;//发布状态 已发布|草稿

    @NotNull
    private Integer categoryId;//文章分类id

    private Integer createUser;//创建人ID
    private 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

    @NotEmpty
    private String categoryName;//分类名称

    @NotEmpty
    private 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 {
    @NonNull
    private 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
    @Email
    private String email;//邮箱

    @URL
    private 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 {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void addArticle(Article article) {
        // 设置发布人的id
        article.setCreateUser(GetNowLoginIdUtil.getID());
        articleMapper.addArticle(article);
    }

    @Override
    public PageBean<Article> findAllArticle(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 创建 PageBean 对象 存储分页数据
        PageBean<Article> pb = new PageBean<>();
        // 开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        // (Page<Article>) 强转: 当使用 PageHelper 分页查询后,会帮我们返回总记录条数和当前页数据
        // 调用 mapper
        Page<Article> pg = (Page<Article>) articleMapper.findAllArticle(GetNowLoginIdUtil.getID(), categoryId, state);

        // 将数据存入 PageBean
        pb.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 {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void add(Category category) {
        Integer id = GetNowLoginIdUtil.getID();
        category.setCreateUser(id);
        categoryMapper.add(category);
    }

    @Override
    public List<Category> findAll() {
        Integer id = GetNowLoginIdUtil.getID();
        return categoryMapper.findAll(id);
    }

    @Override
    public Category findCategoryById(Integer id) {
        return categoryMapper.findCategoryById(id);
    }

    @Override
    public void updateCategory(Category category) {
        categoryMapper.updateCategory(category);
    }

    @Override
    public 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 {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    @Override
    public void registerUser(String username, String password) {
        // 加密
        String md5String = Md5Util.getMD5String(password);
        // 添加
        userMapper.registerUser(username, md5String);
    }

    @Override
    public User getUserInfo(Integer id) {
        return userMapper.getUserInfo(id);
    }

    @Override
    public 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);
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

面试问答总结之并发编程

文章目录 &#x1f412;个人主页&#x1f3c5;JavaEE系列专栏&#x1f4d6;前言&#xff1a;&#x1f380;多线程的优点、缺点&#x1f415;并发编程的核心问题 &#xff1a;不可见性、乱序性、非原子性&#x1fa80;不可见性&#x1fa80;乱序性&#x1fa80;非原子性&#x1…

Linux - 权限概念

Linux下有两种用户&#xff1a;超级用户&#xff08;root&#xff09;、普通用户。 超级用户&#xff1a;可以再linux系统下做任何事情&#xff0c;不受限制普通用户&#xff1a;在linux下做有限的事情超级用户的命令提示符是“#”&#xff0c;普通用户的命令提示符是“$” 命…

深入探究Python多进程编程:Multiprocessing模块基础与实战【第98篇—Multiprocessing模块】

深入探究Python多进程编程&#xff1a;Multiprocessing模块基础与实战 在Python编程中&#xff0c;多进程处理是一项关键的技术&#xff0c;特别是在需要处理大规模数据或执行耗时任务时。为了充分利用多核处理器的优势&#xff0c;Python提供了multiprocessing模块&#xff0…

G8-ACGAN理论

本文为&#x1f517;365天深度学习训练营 中的学习记录博客 原作者&#xff1a;K同学啊|接辅导、项目定制 我的环境&#xff1a; 1.语言&#xff1a;python3.7 2.编译器&#xff1a;pycharm 3.深度学习框架Pytorch 1.8.0cu111 一、对比分析 前面的文章介绍了CGAN&#xf…

Python批量提取文件夹中图片的名称及路径到指定的.txt文件中

目录 一、代码二、提取效果 一、代码 import os# 定义要保存的文件名 file_name "TestImage/Image_Visible_Gray.txt"# 读取文件夹路径 folder_path "TestImage/Image_Visible_Gray"# 遍历文件夹中的所有文件 with open(file_name, "w") as f…

132557-72-3,2,3,3-三甲基-3H-吲哚-5-磺酸,具有优异的反应活性和光学性能

132557-72-3&#xff0c;5-Sulfo-2,3,3-trimethyl indolenine sodium salt&#xff0c;2,3,3-三甲基-3H-吲哚-5-磺酸&#xff0c;具有优异的反应活性和光学性能&#xff0c;一种深棕色粉末 您好&#xff0c;欢迎来到新研之家 文章关键词&#xff1a;132557-72-3&#xff0c;5…

使用maven项目引入jQuery

最近在自学 springBoot &#xff0c;期间准备搞一个前后端不分离的东西&#xff0c;于是需要在 maven 中引入jQuery 依赖&#xff0c;网上百度了很多&#xff0c;这里来做一个总结。 1、pom.xml 导入依赖 打开我们项目的 pom.xml 文件&#xff0c;输入以下坐标。这里我使用的是…

[BUUCTF]-Reverse:reverse3解析

查看ida 从下图的/3和*4可以推断得出来是base64加密。 ida里大致意思就是我们输入的字符串经过base64加密&#xff0c;循环递减&#xff0c;最后等于str2&#xff0c;那我们输入的字符串就是flag。 完整exp&#xff1a; import base64 liste3nifIH9b_CndH print(len(list))fl…

2024年3月腾讯云服务器优惠价格曝光!这价格没谁了

腾讯云优惠活动2024新春采购节活动上线&#xff0c;云服务器价格已经出来了&#xff0c;云服务器61元一年起&#xff0c;配置和价格基本上和上个月没什么变化&#xff0c;但是新增了8888元代金券和会员续费优惠&#xff0c;腾讯云百科txybk.com整理腾讯云最新优惠活动云服务器配…

深度伪造,让网络钓鱼更加难以辨别

网络钓鱼一直是安全领域的一个突出话题&#xff0c;尽管这类诈骗形式已经存在了几十年&#xff0c;依旧是欺诈攻击或渗透组织的最有效方法之一。诈骗分子基于社会工程原理&#xff0c;通过邮件、网站以及电话、短信和社交媒体&#xff0c;利用人性&#xff08;如冲动、不满、好…

智能分析网关V4电瓶车检测与烟火算法,全面提升小区消防安全水平

2024年2月23日&#xff0c;南京市某小区因电瓶车停放处起火引发火灾事故&#xff0c;造成巨大人员伤亡和损失。根据国家消防救援局的统计&#xff0c;2023年全国共接报电动自行车火灾2.1万起。电瓶车火灾事故频发&#xff0c;这不得不引起我们的重视和思考&#xff0c;尤其是在…

用于游戏开发的顶级 PYTHON 框架

一、说明 我们试图用python开发游戏&#xff0c;一旦产生这个念头&#xff0c;就伴随这样一个问题&#xff1a;当今用于构建游戏的领先 Python 框架有哪些&#xff1f;python下&#xff0c;支持游戏开发平台有哪些优势&#xff1f;我们在这篇博文中告诉你。 二、高级游戏平台简…

小甲鱼Python07 函数初级

一、创建和调用函数 pass语句表示一个空的代码块&#xff0c;我们经常先写好函数&#xff0c;pass占一个坑&#xff0c;等规划好之后再来填坑。 函数也是可以指定参数的&#xff0c;我们会把参数传进去用来替代形参。 在Python里如果想要返回值&#xff0c;不需要指定函数的返…

高侧开关芯片四通道 40V 50mΩ车规级带反向电流保护功能负载检测高边开关

概述 PC8845/G是四通道、高侧功率具有集成NMOS功率FET的开关&#xff0c;以及电荷泵。该设备集成了高级 保护功能&#xff0c;例如负载电流限制&#xff0c;通过功率限制进行过载主动管理可配置闩锁关闭的超温停机。全面诊断和高精度电流感应这些功能实现了对负载的智能控制。…

2326. 王者之剑(网络流,最小割,最大权独立集,最小点权覆盖)

活动 - AcWing 给出一个 nm 网格&#xff0c;每个格子上有一个价值 vi,j 的宝石。 Amber 可以自己决定起点&#xff0c;开始时刻为第 0 秒。 以下操作&#xff0c;在每秒内按顺序执行。 若第 i 秒开始时&#xff0c;Amber 在 (x,y)&#xff0c;则 Amber 可以拿走 (x,y) 上的…

LeetCode刷题--- 乘积为正数的最长子数组长度

个人主页&#xff1a;元清加油_【C】,【C语言】,【数据结构与算法】-CSDN博客 个人专栏 力扣递归算法题 http://t.csdnimg.cn/yUl2I 【C】 ​​​​​​http://t.csdnimg.cn/6AbpV 数据结构与算法 ​​​http://t.csdnimg.cn/hKh2l 前言&#xff1a;这个专栏主要讲述动…

3.1作业

作业要求&#xff1a; 通过w(红色臂角度增大)s&#xff08;红色臂角度减小&#xff09;d&#xff08;蓝色臂角度增大&#xff09;a&#xff08;蓝色臂角度减小&#xff09;按键控制机械臂 程序代码&#xff1a; #include<myhead.h> #define SER_IP "192.168.126.…

AGI概念与实现

AGI AGI&#xff08;Artificial General Intelligence&#xff09;&#xff0c;中文名为“通用人工智能”或“强人工智能”&#xff0c;是指通过机器学习和数据分析等技术&#xff0c;使计算机具有类似于人类的认知和学习能力的技术. 多模态的大模型 &#xff08;Multimodal…

VSCode上搭建C/C++开发环境(vscode配置c/c++环境)Windows系统---保姆级教程

引言劝退 VSCode&#xff0c;全称为Visual Studio Code&#xff0c;是由微软开发的一款轻量级&#xff0c;跨平台的代码编辑器。大家能来搜用VSCode配置c/c&#xff0c;想必也知道VSCode的强大&#xff0c;可以手握一个VSCode同时编写如C&#xff0c;C&#xff0c;C#&#xff…

Java SE:多线程(Thread)

1. 线程两个基本概念 并发&#xff1a;即线程交替运行多个指令并行&#xff1a;即多个线程同时运行指令 并发并行不矛盾&#xff0c;两者可同时发生&#xff0c;即多个线程交替运行指令 2. 多线程3种实现方式 2.1 直接创建线程对象 /*** 方式1&#xff1a;* 1. 创建thread类的…