Java 验证请求数据完整性信息

CreditAntifraudReq 请求接收实体类

package com.frms.exchange.command;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.validator.constraints.NotEmpty;

import java.io.Serializable;

@Getter
@Setter
@NoArgsConstructor
/**
 * 请求参数
 */
public class CreditAntifraudReq implements Serializable{

    @NotEmpty(message = "用户ID不能为空")
    private String userId;

    @NotEmpty(message = "欺诈产品类别不能为空")
    private String productType;

    @NotEmpty(message = "姓名不能为空")
    private String name;

    @NotEmpty(message = "身份证号不能为空")
    private String certNo;

    private String mobile;

    private String email;

   }

CreditAntifraudController 前端调用方法实现类

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URLDecoder;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

@Slf4j
@Controller
@RequestMapping("creditAntifraud")
public class CreditAntifraudController {
    @Override
    public CreditAntifraudRes getCreditAntifraud(@RequestBody CreditAntifraudReq CreditAntifraudReq){
        //调用验证方法
        CreditAntifraudRes res = validtateRequest(CreditAntifraudReq);
        if(res == null){
            res = aliPayService.getCreditAntifraud(CreditAntifraudReq);
        }
        return res;
    }

    /**
     * 验证请求数据完整性信息
     *
     * @param req
     */
    private CreditAntifraudRes validtateRequest(CreditAntifraudReq req) {
        Set> violations = validator.validate(req);
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation violation : violations) {
            sb.append(violation.getMessage()).append(";");
        }
        CreditAntifraudRes res = null;
        //如果大于0则有数据为空
        if (sb.length() > 0) {
            res = new CreditAntifraudRes();
            res.setErrorCode("1000");
            res.setErrorMessage(sb.toString());
        }
        return res;
    }
}

你可能感兴趣的:(Java,常用工具)