我发送" application / json"的POST请求用“邮递员”打字,设置参数"电话"要清空字符串,通常它应该为注释打印错误" @ NotEmpty"但是,它没有打印任何内容并且运行良好。
控制器:
@RequestMapping(value = "verify_smscode", method = RequestMethod.POST)
@ResponseBody
public ResponseDto verifySmsCode(HttpServletRequest request,
@Valid @RequestBody VerifySmsCodeParam params, Errors errors) {
if(errors.hasErrors()) {
System.out.println("error");
}
boolean success = userService.verifySmsCode(params.getPhone(), params.getSmsCode());
Map<String, Object> result = new HashMap<>();
result.put("status", success);
return new ResponseDto(result);
}
型号:
@Data
@NoArgsConstructor
public class VerifySmsCodeParam {
@NotEmpty //import org.hibernate.validator.constraints.NotEmpty;
private String phone;
@NotEmpty
private String smsCode;
}
SpringMvcConfig:
@Configuration
@ComponentScan(basePackages="com.shit.voiceshare")
@EnableWebMvc
public class SpringMvcConfig extends WebMvcConfigurerAdapter {
@Override
public Validator getValidator() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.setProviderClass(HibernateValidator.class);
return localValidatorFactoryBean;
}
}
答案 0 :(得分:2)
您可能缺少依赖项。
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
此外,请确保正确导入NotNull
。
import javax.validation.constraints.NotNull;
答案 1 :(得分:0)
我,我在春天还是新人。但如果适合你,这里有一个答案。
要使@Valid工作,你应该包括两个包javax validation-api和hibernate-validator,但我只包括validation-api。
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.1.Final</version>
</dependency>