我正在使用 Spring 验证器进行表单验证。这是我的代码的结构。如您所见,我必须在 POST 方法中手动调用 validate。有什么方法可以让我在不调用 validate() 的情况下将验证器连接到表单处理中?
请注意,我的域对象(MyModel)是一个 POJO,没有任何字段级注释,例如 @NotNull 等。
非常感谢您的帮助!
@Controller
public class FormTest extends MyController {
.....
@Autowired
private MyValidator myValidator; // implementing Spring's Validator interface
......
@RequestMapping(value={"/formtest"}, method=RequestMethod.GET)
public String formGet(HttpServletRequest request,
@RequestParam(value="id", required = false) Long id,
Map<String, Object> map) {
return "/form";
}
@RequestMapping(value={"/formtest"}, method=RequestMethod.POST)
public String formPost(HttpServletRequest request,
@ModelAttribute("command") MyModel m,
@RequestParam(value="id", required = false) Long id,
Map<String, Object> map,
BindingResult result,
SessionStatus status) {
myValidator.validate(m, result); //manual validation
if (result.hasErrors()) {
return "/form";
}
service.saveMyModel(m);
return "redirect:/formtest?id=" + id;
}
@ModelAttribute("command")
public MyModel backingObject(HttpServletRequest request,
@RequestParam(value="id", required = false) Long id) {
MyModel m = null;
if (id != null)
m = service.getMyModel(id);
else
m = new MyModel();
return m;
}
}