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

news2024/11/14 13:41:28

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

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

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

相关文章

HMAC算法

HMAC HMAC可以用来加密、数字签名、报文验证等。 1. 消息认证码 消息认证码&#xff08;Message Authentication Code&#xff0c;MAC&#xff09;是基于消息和秘钥的公开函数&#xff0c;输出为定长数据&#xff1a; MACC(M,K) 假定通信双发共享秘钥K&#xff0c;发送方A向接…

ubuntu22.04 成功编译llvm和clang 3.4.0,及 bitcode 函数名示例,备忘

1, 获取llvm 仓库 从github上获取&#xff1a; $ git clone --recursive https://github.com/llvm/llvm-project.git 2, 检出 llvmorg-3.4.0 tag 针对llvm 3.4.0版本&#xff0c;检出 $ cd llvm-project $ git tag $ git checkout llvmorg-3.4.0 3, 配置并编译llvm 使用 M…

ARK:《BIG IDEAS 2024》

Cathie Wood所带领的方舟投资&#xff08;ARK&#xff09;发布了年度重磅研究报告《BIG IDEAS 2024》&#xff0c;该报告指出人工智能、公共区块链、多组学测序、能源存储和机器人技术这五大板块的融合将带来全球经济活动的改变。 这五个创新平台正在融合并定义这个技术时代&am…

GoFrame:如何简单地搭建一个简单地微服务

一切资料来源于GoFrame官网&#xff0c; 感兴趣的&#xff0c; 可以直接去官网查阅相关资料。 首先下载框架工具&#xff0c; 下载地址&#xff1a;https://github.com/gogf/gf/releases 然后进入你想要放置的项目文件夹&#xff0c; 执行命令行 gf init {project_name} #pr…

插混、油混、增程式、轻混、强混,啥区别

这里写自定义目录标题 随着我国新能源汽车的大力推进&#xff0c;电车可以说是世界未来的主流&#xff0c;只不过现在是处在一个过渡时代 这是个好时代&#xff0c;因为我们见证并体验着历史过渡的细节 这是个不好的时代&#xff0c;因为我们可能只是未来新新人类的试验品 帮他…

微信小程序iOS禁止上下拉显示白边

先上图暴露出问题 iOS端这个页面明明正好显示的&#xff0c;非要能下拉上拉给显示出来点白边。这样不就不好看了嘛。。 想了想是不是支持页面下拉导致的&#xff0c;加入以下代码到json文件中。 {"enablePullDownRefresh": false,"usingComponents": {} }…

【k8s资源调度--DaemonSet】

1、什么是守护进程 有以下这样一个商品场景&#xff1a; 1、用户在商城查询商品信息&#xff0c;查询商品信息的时候需要登录用户&#xff0c;如果用户想要下单&#xff0c;需要提交到订单服务&#xff0c;最后下单完成后&#xff0c;需要更新仓库的商品数量信息。 2、如果每一…

mysql和redis双写一致性策略分析

mysql和redis双写一致性策略分析 一.什么是双写一致性 当我们更新了mysql中的数据后也可以同时保证redis中的数据同步更新&#xff1b; 数据读取的流程&#xff1a; 1.读取redis,如果value!null,直接返回&#xff1b; 2.如果redis中valuenull&#xff0c;读取mysql中数据对应的…

P2040 打开所有的灯

题目传送门&#xff1a;P2040 打开所有的灯 用深度优先搜索实现的一个填色题。 题目步骤&#xff1a; 1..dfs 首先dfs要判断是否符合题意&#xff0c;如果符合题意就更新最短路&#xff1b; 如果不符合题意就枚举 如果是关的就把周围四个包括 给标记上和原来相反的&#xf…

AI大预言模型——ChatGPT与AI绘图及论文高效写作

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

python语言1

一、pytho中的注释 1.1注释的理解 程序员在代码中对代码功能解释说明的标注性文字可以提高代码的可读性注释的内容将被python解释器忽略&#xff0c;不被计算机执行 1.2注释的分类 注释分为&#xff1a;单行注释、多行注释、中文声明注释 &#xff08;1&#xff09;单行注…

计算机网络-网络互连和互联网(五)

1.路由器技术NAT&#xff1a; 网络地址翻译&#xff0c;解决IP短缺&#xff0c;路由器内部和外部地址进行转换。静态地址转换&#xff1a;静态NAT&#xff08;一对一&#xff09; 静态NAT&#xff0c;内外一对一转换&#xff0c;用于web服务器&#xff0c;ftp服务器等固定IP的…

大模型的智慧之源:图技术的崛起

自2023年以来&#xff0c;大语言模型&#xff08;Large Language Models&#xff0c;LLMs&#xff09;的兴起已经改变了科技行业的面貌。 科创公司如果不涉足这一领域&#xff0c;似乎就不好意思称自己是科技企业。 然而&#xff0c;随着大语言模型的普及&#xff0c;它固有的…

Linux高级编程:进程(三),线程(一)

进程的一生&#xff1a; execute&#xff1a; exec族 用fork创建子进程后执行的是和父进程相同的程序&#xff08;但有可能执行不同的代码分支&#xff09;&#xff0c; 子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时&#xff0c;该进程的 用户空间…

Python复合型数据避坑指南

目录 前言 列表&#xff08;Lists&#xff09; 1. 修改可变对象 2. 浅拷贝和深拷贝 元组&#xff08;Tuples&#xff09; 集合&#xff08;Sets&#xff09; 字典&#xff08;Dictionaries&#xff09; 1. 键值唯一性 2. 键的类型 实际应用场景 1. 数据分析与清洗 2. 网络…

微信小程序云开发教程——墨刀原型工具入门(安装以及基础使用教程)

引言 作为一个小白&#xff0c;小北要怎么在短时间内快速学会微信小程序原型设计&#xff1f; “时间紧&#xff0c;任务重”&#xff0c;这意味着学习时必须把握微信小程序原型设计中的重点、难点&#xff0c;而非面面俱到。 要在短时间内理解、掌握一个工具的使用&#xf…

Hgame题解(第二星期)

Hgame题解&#xff08;第二星期&#xff09; Web Select More Courses 打开靶机发现是一个登陆页面&#xff0c;根据题目提示下载弱密码字典&#xff0c;通过BP爆破获得用户密码为qwert123 登陆后进入下一个页面&#xff0c;由于学分已满无法选课&#xff0c;所以需要先进行…

仿牛客网项目---显示评论和添加评论功能的实现

这篇文章&#xff0c;我来介绍一下我的项目中的另外一个功能&#xff1a;显示评论和添加评论。 其实这两个功能都不怎么重要&#xff0c;我感觉最重要的应该是用户注册登录功能&#xff0c;这个也了解一下&#xff0c;知道这么一回事儿就好。 首先设计DAO层。 Mapper public …

【刷题】Leetcode 1609.奇偶树

Leetcode 1609.奇偶树 题目描述广度优先搜索&#xff08;BFS&#xff09;深度优先算法&#xff08;DFS&#xff09; 思路一&#xff08;BFS&#xff09;思路二&#xff08;DFS&#xff09;Thanks♪(&#xff65;ω&#xff65;)&#xff89;谢谢阅读&#xff01;&#xff01;&a…

配置之道:深入研究Netty中的Option选项

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 配置之道&#xff1a;深入研究Netty中的Option选项 前言Option的基础概念ChannelOption与Bootstrap Option常见的ChannelOption类型ChannelConfig的使用Option的生命周期不同传输协议的Option 前言 在…