我有一個帶有HTML/endoUI UI的SpringMVC 3.2服務,我無法返回消息。看起來,我填充的RequestAttributes對Javascript不可見。我所看到的SpringMVC錯誤處理的所有示例都使用html或jsp重定向。使用JavaScript UI的SpringMVC錯誤處理
這裏有一個例子:
@Controller
@RequestMapping("/officeSignUp")
public class OfficeSignUpController
..
@RequestMapping(value = "/stepOne", method = RequestMethod.POST)
@ResponseBody
public String officeCreationStepOne(@Valid @ModelAttribute("officeSetup") OfficeSetup officeSetup,
BindingResult result, Model model, RedirectAttributes attributes) {
String results;
results = newOfficeValidator.validateStepOne(officeSetup, result);
NewCustomerSignup newCustSignup = newOfficeValidator.validateNewOwner(officeSetup);
model.addAttribute(newCustomerSignupRepository.save(newCustSignup));
return results;
}
我的驗證是:
@Component 公共類NewOfficeValidator {
public String validateStepOne(OfficeSetup officeSetup, BindingResult result) {
List<String> errors = new ArrayList<String>();
if (result.hasErrors()) {
for (ObjectError error : result.getAllErrors()) {
errors.add(error.getDefaultMessage());
}
errors.add("redirect: " + VIEW_STEP_ONE);
// RuntimeException with a list of strings in it
throw new OfficeSetupException(errors, "Validation in StepOne");
}
return VIEW_STEP_TWO;
}
在我BaseController我捕捉到了異常,檢索錯誤消息並使用它們:
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorMessage handleOfficeSetupException(OfficeSetupException ex) {
List<String> errors = ex.getErrors();
StringBuilder sb = new StringBuilder();
for (String error : errors) {
sb.append(error);
}
// this is just a bean with a list of Strings
return new ErrorMessage(errors);
}
當一個異常被拋出,而不是一個JSON或字符串的反應,我得到它包含了tomcat HTML郵件:
<h1>HTTP Status 400 - Received OfficeSetupException </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Received OfficeSetupException </u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect (Received OfficeSetupException).</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.27</h3></body></html>
,然後在JavaScript:
if(stepString == "Step 2"){ click on step 2
if(viewModelStepOne.validateStepOne(s) == true){ client side validation
viewModelStepOne.saveStepOne(s);if above validation passes, send request to server,
if(serverValidationFailed){if server returns error, do not move to step 2
s.preventDefault();
}else{ move to step
this.disable(this.tabGroup.children("li").eq(2),true);
this.enable(this.tabGroup.children("li").eq(3),true);
}
}else{ s.preventDefault();
}
}
所以,最後我問題是:從spring mvc到javascript前端返回驗證或其他錯誤消息的最佳方式是什麼?我想爲我的回覆使用JSON,所以我希望ErrorMessage能夠被返回。
我注意到您在使用@ResponseBody註解的處理程序方法中使用model.addAttribute(...)。這是爲什麼? (模型用於訪問數據,但您沒有使用視圖)。 –