我想做的是在发生错误时更换整个表单.以下是超原始示例.我不会使用大量的片段来呈现一个表单…只是保持简单.
这是写在Spring 4.2.1和Thymeleaf 2.1.4中
表示用户信息表单的基本类:UserInfo.java
package myapp.forms;
import org.hibernate.validator.constraints.Email;
import javax.validation.constraints.Size;
import lombok.Data;
@Data
public class UserInfo {
private String email;
@Size(min = 1,message = "First name cannot be blank")
private String firstName;
}
控制器:UsersAjaxController.java
import myapp.forms.UserInfo;
import myapp.services.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.transaction.Transactional;
@Controller
@Transactional
@RequestMapping("/async/users")
public class UsersAjaxController {
@Autowired
private UserServices userServices;
@RequestMapping(value = "/saveUserInfo",method = RequestMethod.POST)
public String saveUserInfo(@Valid @modelattribute("userInfo") UserInfo userInfo,BindingResult result,Model model) {
// if any errors,re-render the user info edit form
if (result.hasErrors()) {
return "fragments/user :: info-form";
}
// let the service layer handle the saving of the validated form fields
userServices.saveUserInfo(userInfo);
return "fragments/user :: info-success";
}
}
用于呈现表单和成功消息的文件:fragments / user.html
First Name
Form successfully submitted
JS代码将简单地将表单提交到表单action属性中提供的URL.当响应返回到JS回调时,检查是否有任何错误.如果有错误,请将表单替换为响应中的表单.
(function($){
var $form = $('#userInfo');
$form.on('submit',function(e) {
e.preventDefault();
$.ajax({
url: $form.attr('action'),type: 'post',data: $form.serialize(),success: function(response) {
// if the response contains any errors,replace the form
if ($(response).find('.has-error').length) {
$form.replaceWith(response);
} else {
// in this case we can actually replace the form
// with the response as well,unless we want to
// show the success message a different way
}
}
});
}(jQuery));
再次,这只是一个基本的例子.如上述评论中所提到的,没有正确的或错误的方法来解决这个问题.这不是我的首选解决方案,绝对有一些调整,我会做,但一般的想法是在那里.
注意:我的JS代码中还有一个缺陷.如果将表单与响应中的表单替换,则表单提交处理程序将不会应用于新替换的表单.如果进入此路由,则需要确保在更换表单后正确重新初始化表单处理程序.