1

我正在使用 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;
    }
}
4

1 回答 1

1

你可以这样做:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveEntity(@Valid Entity entity, BindingResult result) {
    if (result.hasErrors()) {
           // do something
    }
    // do something else
}

并且控制器中还需要其他方法来注册您的验证器:

@InitBinder("entity")
public void initBinder(WebDataBinder binder) {
    binder.setValidator(new EntityValidator());
}
于 2013-05-11T21:44:27.767 回答