#validator #springboot

Spring boot 利用Javax進行群組約束

莊雅卉 Catherine Jhuang 2021/11/05 17:00:21
149

 

一、目的:
利用javax進行群組約束,達到驗證請求欄位之驗測。
Grouping Javax Validation Constraints

二、建置環境:

  1. Spring boot 2.4.1
  2. Maven
  3. java 8

三、開發工具

  1. IntelliJ idea

四、專案架構
/tpu/File/html/202110/20211014152646/images/20211013155844.png

五、步驟

  1. 添加依賴
    pom.xml

<dependency>

        <groupId>org.hibernate</groupId>

        <artifactId>hibernate-validator</artifactId>

        <version>6.0.17.Final</version>

</dependency>

  1. Request中添加驗證群組
    MemberReq.java

import com.docker.image.model.dto.common.ReqView;

import com.fasterxml.jackson.annotation.JsonView;

import lombok.Data;

 

import javax.validation.constraints.NotNull;

 

 

@Data

public class MemberReq {

    public interface ValidatorUpdateName {}

    public interface ValidatorGet {}

    public interface ValidatorAdd {}

 

    @JsonView(ReqView.MemberId.class)

    @NotNull(groups = {ValidatorUpdateName.class,ValidatorGet.class})

    private Integer id;

 

    @JsonView(ReqView.MemberName.class)

    @NotNull(groups = {ValidatorUpdateName.class,ValidatorAdd.class})

    private String name;

 

    @JsonView(ReqView.Member.class)

    @NotNull(groups = {ValidatorAdd.class})

    private String password;

}

3.資料處理層
MemberServiceImpl.java

public MemberRes updateName(MemberReq memberReq){

        Member member =  memberRepository.findById(memberReq.getId()).get();

        member.setName(memberReq.getName());

        memberRepository.save(member);

        return ObjectUtils.mapDaoToDtoWithView(member, MemberRes.class,ResView.Member.class);

    }

  1. controller添加驗證機制
    MemberController.java

@PutMapping(value = "/update")

    @JsonView(ResView.MemberName.class)

    public MemberRes updateName(

            @Validated({MemberReq.ValidatorUpdateName.class})

            @RequestBody MemberReq memberReq){

        return memberService.updateName(memberReq);

    }

  1. 完成驗證機制
    若是Request中有欄位不符合規定,即報錯。

  2. 成功!

 

 

 

 

莊雅卉 Catherine Jhuang