我有一個使用豆驗證來驗證輸入的值,例如,以節省一個話題的彈簧控制器:春季ExceptionHandler訪問模型?
public String save(@ModelAttribute("topic") @Valid Topic topic
這很好地工作。
在我的數據層我也使用Bean驗證和當事情無效是發送到數據層ConstraintViolationException被拋出。我用異常處理程序在我的控制器中捕獲了這一個:
@ExceptionHandler({ ConstraintViolationException.class })
public ModelAndView handleValidationException(HttpServletRequest req,ConstraintViolationException e) {
這也很好。
我現在面臨的問題是我不能訪問該模型在我的ExceptionHandler,該文檔明確指出這一點:
因爲我想顯示用戶視圖需要Important Note: the Model may not be a parameter of any @ExceptionHandler method.
訪問模型與他剛剛填寫的表單。但因爲我無法訪問模型,我無法獲取填寫的表單數據。
一個解決方案,我發現正趕上我的save()方法的ConstraintViolationException,造成這裏我有訪問模型。
但我寧願一個通用的解決方案,並沒有凌亂的try/catch /終於,當我需要的東西保存到數據庫中。
有沒有人知道一個好的解決方案?
[編輯] 這是我當前的異常處理程序:
@ExceptionHandler({ ConstraintViolationException.class })
public ModelAndView handleValidationException(HttpServletRequest req,ConstraintViolationException e) {
log.debug("handleValidationException");
//no access to model, so i create new one, but this new one doesn't have the values the user entered in the html form.
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.setViewName("add_topc");
return mav;
}
我們可以看到你'@ ExceptionHandler'是幹什麼的? 「主題」對象應該已經在模型中。 –
我已將異常處理程序添加到問題中。正如在文檔中寫的,並在我的問題中指出的那樣:「模型可能不是任何@ExceptionHandler方法的參數。」如果我明白正確的Topic對象在exceptionhandler中不可用,導致持有Topic對象的模型在exceptionhandler中不可用。 – TinusSky
對於實際的'Topic'對象有什麼要做的嗎?您從'@ ExceptionHandler'返回的'ModelAndView'將與您的'@ Controller'處理程序方法使用的'Model'合併。 –