【第10章】SpringBoot实战篇之文章(上)含自定义校验


前言

文章内容分为上下两篇,上篇搭建文章后端代码结构和新增接口,下篇介绍更多功能。


一、自定义校验

1. 自定义注解

package org.example.springboot3.bigevent.valid;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Create by zjg on 2024/5/28
 */
@Documented
@Constraint(
        validatedBy = {ArticleStateValidator.class}
)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ArticleState {
    String message() default "state参数只能为草稿或者已发布";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

2. 自定义校验类

package org.example.springboot3.bigevent.valid;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.util.StringUtils;

/**
 * Create by zjg on 2024/5/28
 */
public class ArticleStateValidator implements ConstraintValidator<ArticleState,String> {
    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if(StringUtils.hasLength(s)){
            if("草稿".equals(s)||"已发布".equals(s)){
                return true;
            }
        }
        return false;
    }
}

二、业务代码

1. ArticleController

package org.example.springboot3.bigevent.controller;

import org.example.springboot3.bigevent.entity.Article;
import org.example.springboot3.bigevent.entity.Result;
import org.example.springboot3.bigevent.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Create by zjg on 2024/5/26
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    @PostMapping
    public Result add(@RequestBody @Validated Article article){
        int i = articleService.insert(article);
        if(i!=1){
            return Result.error("新增文章失败");
        }
        return Result.success("新增文章成功");
    }
}

2.ArticleService

package org.example.springboot3.bigevent.service;

import org.example.springboot3.bigevent.entity.Article;

/**
 * Create by zjg on 2024/5/28
 */
public interface ArticleService {
    int insert(Article article);
}

package org.example.springboot3.bigevent.service.impl;

import org.example.springboot3.bigevent.entity.Article;
import org.example.springboot3.bigevent.mapper.ArticleMapper;
import org.example.springboot3.bigevent.service.ArticleService;
import org.example.springboot3.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * Create by zjg on 2024/5/28
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    ArticleMapper articleMapper;

    @Override
    public int insert(Article article) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("userId");
        article.setCreateUser(userId);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        return articleMapper.insert(article);
    }
}

3. ArticleMapper

package org.example.springboot3.bigevent.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.example.springboot3.bigevent.entity.Article;

/**
 * Create by zjg on 2024/5/28
 */
@Mapper
public interface ArticleMapper extends BaseMapper<Article> {
}

4. Article

package org.example.springboot3.bigevent.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.example.springboot3.bigevent.valid.ArticleState;
import java.time.LocalDateTime;

@Getter
@Setter
@ToString
public class Article {
    @TableId(type = IdType.AUTO)
    private Integer id;//主键ID
    @Pattern(regexp = "^\\S{1,10}$",message = "文章标题为1-10个字符")
    @NotEmpty(message = "文章标题不能为空")
    private String title;//文章标题
    @NotEmpty(message = "文章内容不能为空")
    private String content;//文章内容
    @Pattern(regexp = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$",message = "封面图像格式应为http链接")
    private String coverImg;//封面图像
    @ArticleState
    private String state;//发布状态 已发布|草稿
    private Integer categoryId;//文章分类id
    private Integer createUser;//创建人ID
    private LocalDateTime createTime;//创建时间
    private LocalDateTime updateTime;//更新时间
}

三、测试

1.请求

在这里插入图片描述

2.数据

在这里插入图片描述


总结

回到顶部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值