AbstractFormController用于支持带步骤的表单提交的命令控制器基类,使用该控制器可以完成:
- 定义表单处理(表单的渲染),并从控制器获取命令对象构建表单;
- 提交表单处理,当用户提交表单内容后,AbstractFormController可以将用户请求的数据绑定到命令对象,并可以验证表单内容、对命令对象进行处理。
集成 AbstractFormController 类,需要实现其中的handleRequestInternal方法:
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
//1、是否是表单提交? 该方法实现为("POST".equals(request.getMethod())),即POST表示表单提交
if (isFormSubmission(request)) {
try {
Object command = getCommand(request);
ServletRequestDataBinder binder = bindAndValidate(request, command);
BindException errors = new BindException(binder.getBindingResult());
//表单提交应该放到该方法实现
return processFormSubmission(request, response, command, errors);
}
catch (HttpSessionRequiredException ex) {
//省略部分代码
return handleInvalidSubmit(request, response);
}
}
else {
//2、表示是表单展示,该方法又转调showForm方法,因此我们需要覆盖showForm来完成表单展示
return showNewForm(request, response);
}
}
- bindOnNewForm:是否在进行表单展示时绑定请求参数到表单对象,默认false,不绑定;
- sessionForm:session表单模式,如果开启(true)则会将表单对象放置到session中,从而可以跨越多次请求保证数据不丢失(多步骤表单常使用该方式,详解AbstractWizardFormController),默认false;
- Object formBackingObject(HttpServletRequest request) :提供给表单展示时使用的表单对象(form object表单要展示的默认数据),默认通过commandName暴露到请求给展示表单;
- Map referenceData(HttpServletRequest request, Object command, Errors errors):展示表单时需要的一些引用数据(比如用户注册,可能需要选择工作地点,这些数据可以通过该方法提供),如:
protected Map referenceData(HttpServletRequest request) throws Exception {
Map model = new HashMap();
model.put("cityList", cityList);
return model;
}
这样就可以在表单展示页面获取cityList数据。

: » 详解Spring MVC中的AbstractFormController
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/251625.html