我尝试了以下方法。但是,当通过 location.href 移动视图时,不会维护模型和绑定结果。如何维护模型和绑定结果? 也许方法是错误的...
@PostMapping("/example")
@ResponseBody
public Map<String, Object> example(
@RequestPart("formRequest") @Validated FormRequest formRequest,
BindingResult bindingResult,
@RequestPart(value = "file", required = false) MultipartFile file,
@RequestPart(value = "files", required = false) MultipartFile[] files,
Model model
) {
Map<String, Object> response = new HashMap<>();
if (bindingResult.hasErrors()) {
log.warn("bindingResult={}", bindingResult);
model.addAttribute("formRequest", formRequest);
model.addAttribute("formStatus", FormStatus.CREATE);
response.put("errors", bindingResult.getAllErrors());
response.put("url", "/example");
return response;
}
return response;
}
$.ajax({
url: url,
type: "POST",
data: formData,
enctype: "multipart/form-data",
contentType: false,
processData: false,
success: function (response) {
location.href = response.url;
}
});
当您使用
location.href
重定向页面时,当前页面将重新加载,模型或 BindingResult
中存储的所有数据都会丢失。在请求之间维护数据的一种方法是将其存储在会话中或将其作为 URL 参数传递。
在您的情况下,您可以修改控制器以将
formRequest
和 bindingResult
对象存储在会话中,然后在渲染视图时从会话中检索它们。修改您的代码如下:
@PostMapping("/example")
@ResponseBody
public Map<String, Object> example(
@RequestPart("formRequest") @Validated FormRequest formRequest,
BindingResult bindingResult,
@RequestPart(value = "file", required = false) MultipartFile file,
@RequestPart(value = "files", required = false) MultipartFile[] files,
Model model,
HttpSession session
) {
Map<String, Object> response = new HashMap<>();
if (bindingResult.hasErrors()) {
log.warn("bindingResult={}", bindingResult);
// Store formRequest and bindingResult in the session
session.setAttribute("formRequest", formRequest);
session.setAttribute("bindingResult", bindingResult);
response.put("errors", bindingResult.getAllErrors());
response.put("url", "/example");
return response;
}
return response;
}
然后在您的视图中,您可以从会话中检索
formRequest
和 bindingResult
对象并使用它们。