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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangbinlong/article/details/78607639

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<ConstraintViolation<CreditAntifraudReq>> violations = validator.validate(req);
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<CreditAntifraudReq> 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;
    }
}

猜你喜欢

转载自blog.csdn.net/zhangbinlong/article/details/78607639