带有JavaScript UI的SpringMVC错误处理

SpringMVC ErrorHandling with JavaScript UI

本文关键字:错误 处理 SpringMVC JavaScript UI 带有      更新时间:2023-09-26

我有一个SpringMVC 3.2服务,它带有HTML/endoUI UI,我无法向其返回消息。我填充的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;
}

我的验证器是:

@组件公共类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();
    }
}

因此,最终我的问题是:从springmvc向javascript前端返回验证或其他错误消息的最佳方式是什么?我正在尝试使用JSON作为响应,所以我希望ErrorMessage也能这样返回。

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

我想我通过在异常中添加"@JsonAutoDetect"解决了这个问题。我使用的是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;
    }
}