0 背景
用来对上传属性进行判断,例如上传对象的名称重复验证
1 新建VoValidator类
import io.transwarp.zjnx.domain.ExperimentDesignVo;
import io.transwarp.zjnx.repository.ExperimentDesignRepository;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* @author my
* @description
* @date 2020/6/27 13:54
*/
@Component
public class VoValidator implements Validator {
private ExperimentDesignRepository experimentDesignRepository;
public VoValidator(ExperimentDesignRepository experimentDesignRepository){
this.experimentDesignRepository = experimentDesignRepository;
}
@Override
public boolean supports(Class<?> clazz) {
return ExperimentDesignVo.class.equals(clazz);
}
/**
* 在这里判断名称不可重复(Vo类属性的@Size(max=20)和@NotEmpty也从这里判断)
* @param target
* @param errors
*/
@Override
public void validate(Object target, Errors errors) {
// 接收的类对象
ExperimentDesignVo experimentDesignVo = (ExperimentDesignVo) target;
// 自定义方法
Integer num = experimentDesignRepository.countByName(experimentDesignVo.getName());
if (num >0 ){
errors.rejectValue("name","实验名称已存在");
}
// 用户名和密码判断
// UserCommand user = (UserCommand) target;
// User newUser = userRepository.findByUsername(user.getUsername());
// if (newUser != null && !Objects.equals(newUser.getId(), user.getId())) {
// errors.rejectValue("username", "constraints.user.username.exists","用户名已存在");
// }
// if (user.getRePassword() != null && !user.getPassword().equals(user.getRePassword())) {
// errors.rejectValue("rePassword", "constraints.user.rePassword.notEqualsToPassword","两次密码输入不一致");
// }
}
}
2 VoController类
@Autowired
VoValidator voValidator;
@InitBinder("experimentDesignVo") //确保只拦截指定model
public void initBinder(DataBinder binder){
binder.addValidators(voValidator);
}
@PostMapping("/create")
public ResponseEntity create(@Valid ExperimentDesignVo experimentDesignVo, BindingResult bindingResult){
// 返回到前端的状态,可从中提取错误状态进行tips提示
if (bindingResult.hasErrors()) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON)
.body(bindingResult.getAllErrors());
}
return ResponseEntity.ok().build();
}
3 前端js对返回状态进行处理
<script>
$("#createBtn").click(function(){
$("#createForm").ajaxSubmit({
dataType:"json",
success:function(res){
alertMsg("新建成功","success");
},
// 返回的错误信息,解析可用
error:function(res){
validator(res)
}
})
});
function validator(res){
var obj = res.responseJSON[0];
if( typeof(obj) !== "undefined"){
var field = obj.field;
var code = obj.code;
var objText = $("[name="+filed+"]").parent("div.form_input").find("p>span").text();
var objMsg = code;
if(code === "NotEmpty"){
objMsg = "不能为空";
}
if(code === "Size"){
objMsg = "长度不和规范";
}
alertMsg(objText + objMsg );
}else{
alertMsg(res.responseJSON.error,"error" );
}
}
</script>