簡體   English   中英

將Spring MVC異常作為驗證錯誤處理

[英]Handling Spring MVC Exception as Validation Error

我目前有一個Spring MVC servlet,它處理通過初始表單頁面上傳的文件。

如果請求處理程序缺少某些要求,它已經對文件進行了一些驗證,但不幸的是,在處理實際發生之前,它無法輕易判斷是否滿足所有要求。

@RequestMapping(path = "/", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String submit(@Valid FormData form, BindingResult result, Model model) throws IOException, ParseException
{
   if (result.hasErrors())
   {
      return "index";
   }

   processFile(form.getFile());

   return "success";
}

如果在處理步驟中發生異常,我會在@ExceptionHandler注釋方法中處理它。 但是,此方法需要第二行來顯示JSP頁面中的錯誤:

<form:input type="file" name="file" path="file" value=""/>
<form:errors path="file" element="label" class="error" for="file"/>
<c:if test="${not empty error}"><label class="error">${error}</label></c:if>

用方法本身看起來像

@ExceptionHandler(Exception.class)
public String databaseError(Model model, Exception e)
{
   model.addAttribute("formData", new FormData());
   model.addAttribute("error", "File failed to process. Please verify the contents of the file.");
   return "index";
}

有沒有辦法利用BindingResult處理異常作為驗證錯誤,以避免冗余錯誤消息模板?

您可以在請求處理方法中捕獲異常,然后在catch子句中操作BindingResult。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM