[置顶] java validation 的使用

工具类,自动进行判断
import com.gomefinance.jie.reserveFunds.common.constant.StatusCode;
import com.gomefinance.jie.reserveFunds.dto.BaseResponDTO;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
* Created by Administrator on 17/5/10.
*/
public class ValidationUtil {
private static Validator validator;

static {
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
validator = vf.getValidator();
}

/**
* @Description: 校验方法
* @param t 将要校验的对象
* void
* @throws
*/
public static <T> BaseResponDTO validate(T t){
Set<ConstraintViolation<T>> set = validator.validate(t);
StringBuilder validateError = new StringBuilder();
if(set.size()>0){
for(ConstraintViolation<T> val : set){
validateError.append(val.getMessage() + " ;");
break;
}
return new BaseResponDTO(StatusCode.ONLINE_LOAN_0022.getCode(),validateError.toString());
}else{
return new BaseResponDTO(StatusCode.ONLINE_LOAN_0000);
}
}
}

model类
import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * Created by Administrator on 17/5/9.
 */
public class LoanSpeedReqParamDTO implements Serializable{
    private static final long serialVersionUID = -3725976862025058255L;
    @NotNull(message = "订单号不能为空")
    private String channelOrderId;
    @NotNull(message = "终端标识不能为空")
    private String terminalType;
    private String planCurrTerm;

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public String getChannelOrderId() {
        return channelOrderId;
    }

    public void setChannelOrderId(String channelOrderId) {
        this.channelOrderId = channelOrderId;
    }

    public String getTerminalType() {
        return terminalType;
    }

    public void setTerminalType(String terminalType) {
        this.terminalType = terminalType;
    }

	public String getPlanCurrTerm() {
		return planCurrTerm;
	}

	public void setPlanCurrTerm(String planCurrTerm) {
		this.planCurrTerm = planCurrTerm;
	}


你可能感兴趣的:(java,接口,validation,判断,非空)