[英]Spring boot - NotEmpty annotation only for a specific Controller
I have a form class like this: 我有一个这样的表单类:
public class ProjectForm {
@NotEmpty
private String name;
@NotEmpty
private String desription;
// getters and setters
}
this form is used to both create and edit Project objects which will be saved in a database. 此表单用于创建和编辑将保存在数据库中的Project对象。
I have two different controllers for creating and editing project objects. 我有两个用于创建和编辑项目对象的控制器。
@PostMapping("/projects/edit/{id}")
public String editProject(@Valid ProjectForm projectForm, BindingResult bindingResult, @PathVariable("id") String id) {
//Controller code here
}
and 和
@PostMapping("/projects/new")
public String addProject(@Valid ProjectForm projectForm, BindingResult bindingResult) {
//Controller code here
}
As you see, both controllers use the ProjectForm class. 如您所见,两个控制器都使用ProjectForm类。 How can I make the name field for the first controller mandatory and for the second one optional?
如何使第一个控制器的名称字段为必需字段,第二个控制器的名称字段为可选字段?
You named both of your methods as editProject but I assume only the first one is for editing. 您将两个方法都命名为editProject,但是我假设只有第一个方法才能进行编辑。 As a solution, you can create another class just for editing without using @NotEmpty annotation say, ProjectFormWrapper.
作为解决方案,您可以创建另一个仅用于编辑的类,而无需使用@NotEmpty批注(例如ProjectFormWrapper)。 Other than that, if you are editing an object don't use POST, use PUT.
除此之外,如果您编辑的对象不使用POST,请使用PUT。
Yes u can do it using validation-groups.see this docs validation-groups-docs 是的,您可以使用validation-groups进行此操作。请参阅此文档validation-groups-docs
public interface FirstValidation{
}
public class ProjectForm {
@NotEmpty(groups = {FirstValidation.class},message = "Name can not be empty")
private String name;
@NotEmpty
private String desription;
// getters and setters
}
@PostMapping("/projects/edit/{id}")
public String editProject(@Validated(FirstValidation.class) ProjectForm projectForm, BindingResult bindingResult, @PathVariable("id") String id) {
//Controller code here
}
@PostMapping("/projects/new")
public String addProject(@Valid ProjectForm projectForm, BindingResult bindingResult) {
//Controller code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.