我有一个带有 HTML/endoUI UI 的 SpringMVC 3.2 服务,我无法向其返回消息。我填充的 RequestAttributes 似乎对 Javascript 不可见。我看到的所有 SpringMVC 错误处理示例都使用 html 或 jsp 重定向。
这是一个示例:
@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 会这样返回。