使用JavaScript UI的SpringMVC ErrorHandling

时间:2013-08-28 02:31:36

标签: javascript jquery spring-mvc kendo-ui

我有一个带有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可以这样返回。

2 个答案:

答案 0 :(得分:1)

在我的项目中,我按照你的描述进行操作 - 抛出一个异常并用@ExceptionHandler捕获它。但是您不需要只返回一个字符串消息。创建自己的异常类,可以将Map或Error of errors作为参数(或者您想要用作错误模型的任何其他内容)。当发生错误时,使用错误填充自定义execption(让我们称之为RequestException),然后抛出它。错误将存储在您的exeception实例中。在RequestException的@ExceptionHandler中,从异常对象中获取错误,然后以方便的方式返回前端。

答案 1 :(得分:0)

我想通过将“@JsonAutoDetect”添加到我的Exception来解决它。我正在使用Java Config,因此以下内容似乎可以处理HTTP响应代码并返回JSON响应。

@JsonAutoDetect( fieldVisibility = Visibility.DEFAULT, getterVisibility = Visibility.DEFAULT, isGetterVisibility = Visibility.DEFAULT )
public class OfficeSetupException extends RuntimeException {

    private List<String> errors;

    private static final long serialVersionUID = -1L;

    public OfficeSetupException( List<String> errors, String message ) {
        super( message );
        this.errors = errors;
    }

    public List<String> getErrors() {
        return errors;
    }

}