下面是我的DTO课程。
public class AbstractDTO extends BaseDTO {
private Integer createdBy;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_FORMAT)
@NotNull(message = "createdDate may not be null")
private LocalDateTime createdDate;
private Integer lastModifiedBy;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_FORMAT)
private LocalDateTime lastModifiedDate;
private Boolean isActive;
// getter & setters
}
在这里,我尝试将createdDate字段注释为@NotNull,但它不起作用。它允许在请求正文中,并且在邮递员中执行服务后没有出现任何错误。
我尝试了以下选项,但是没有运气。
1)尝试添加Maven依赖项。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
2)尝试将DTO类注释为@Validated
3)尝试使用@NotNull注释createdDate字段@Valid,但仍然不走运。
请帮助我解决此问题。
答案 0 :(得分:1)
您导入正确吗?
我使用import javax.validation.constraints.NotNull;
答案 1 :(得分:1)
您的DTO是正确的。
来自Spring Boot Validating Form Input Example :
使用public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException {
String url = new GoogleBrowserClientRequestUrl("812741506391.apps.googleusercontent.com",
"https://oauth2.example.com/oauthcallback", Arrays.asList(
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile")).setState("/profile").build();
response.sendRedirect(url);
}
注释。
例如:
@Valid
为什么要使用@Controller
public class Controller {
@PostMapping("/")
public String checkPersonInfo(@Valid AbstractDTO abstractDTO, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "page";
}
return "";
}
}
注释? -这使您可以验证应用于类的数据成员的一组约束。
此外,您必须在applicationContext.xml(源:here)中添加以下内容:
@Valid
答案 2 :(得分:1)
您有一个带有某些请求正文的端点;
@RestController
public class TheController {
@PostMapping(path = "/doSomething", consumes = "application/json", produces = "application/json")
public void post(@Valid @RequestBody AbstractDTO request) {
//code
}
}
您需要为请求对象添加@Valid
注释。只有这样,您才能为AbstractDTO
端点的/doSomething
启用验证。
选中here,以获取更多详细信息