我有这个。
public class ExampleForm implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer idexample;
private String name;
private SomeEntity1 someEntity1;
private SomeEntity2 someEntity2;
// Constructor, getters and setters...
}
我在jsp中有2个表单,第一个使用SomeEntity1
而第二个使用SomeEntity2
。如何在同一个控制器中进行单独验证?这是可能的?。我的主要问题是,如果我尝试有效SomeEntity2
它会尝试使第一个有效并且是空的。
编辑:添加了控制器代码。
@InitBinder
protected void initBinder(final WebDataBinder binder) {
final CustomDateEditor editor = new CustomDateEditor(dateFormat, true);
binder.registerCustomEditor(Date.class, editor);
if (binder.getTarget() instanceof ExampleForm) {
binder.setValidator(this.ExampleValidator);
}
}
@RequestMapping(value = "/ex/addEntity1", method = RequestMethod.GET)
public String addfirst(@Valid @ModelAttribute final ExampleForm exampleForm, final ModelMap model, final HttpSession session) {
//Do some stuff
}
@RequestMapping(value = "/ex/addEntity2", method = RequestMethod.GET)
public String addsecond(@Valid @ModelAttribute final ExampleForm exampleForm, final ModelMap model, final HttpSession session) {
//Do some stuff
}
答案 0 :(得分:1)
在您的情况下,为每个实体实现不同的Validator
而不是使用@Valid
注释可能很有用。
然后在你的控制器方法中,代码类似:
public String addEntityX(@ModelAttribute final ExampleForm exampleForm, BindingResult result) {
new EntityXValidator().validate(exampleForm, result);
if (result.hasErrors()) {
// ...
}
else{
// ...
}
// ...
}
答案 1 :(得分:0)
如果您使用异或外键,您的数据模型可能是错误的。使用继承。您还应该使用POST而不是GET来提交表单。
您应该使用验证组和Spring的@Validated注释:
Scenario1.class:
public interface Scenario1 extends Default() {};
Scenario2.class:
public interface Scenario2 extends Default() {};
ExampleForm.class:
public class ExampleForm implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer idexample;
private String name;
@NotNull( groups = { Scenario1.class } )
private SomeEntity1 someEntity1;
@NotNull( groups = { Scenario2.class } )
private SomeEntity2 someEntity2;
// Constructor, getters and setters...
}
控制器:
/* if users clicks submit button named "scenario1" */
@RequestMapping( method = RequestMethod.POST, params="scenario1" )
String publish( @Validated({Scenario1.class}) ExampleForm exampleForm, BindingResult result)) {
...
}
/* if user clicks submit button named "scenario2" */
@RequestMapping( method = RequestMethod.POST, params="scenario2" )
String publish( @Validated({Scenario2.class}) ExampleForm exampleForm, BindingResult result)) {
...
}