2015-09-09 14 views
0

在我的控制器錯誤,我有無處不在:春BindingResult自動檢查

if(result.hasErrors()) { 
    return "redirect:/foo/bar"; 
    } 

是否有辦法來自動重定向到URI?我想,如果我可以創建和註釋要做到這一點,是這樣的:

@HasErrors(redirect="/foo/bar") 

回答

0

你需要一個異常處理機制來處理假設像這樣在你的控制器錯誤:

@RequestMapping(value = "/checkError") 
public ModelAndView process() throws Exception { 
     User user = new User(); 

     if (user==null) { 
      throw new GlobalExceptionHandler (); // throws GlobalDefaultExceptionHandler 
     } 

     // do something when there isn't error 

} 

並假設這個異常(CustomeException類),將被拋出,而當這個類拋出,你將通過全局異常

@ControllerAdvice 
public class GlobalExceptionHandler { 

    @ExceptionHandler(Exception.class) 
     public String handleException(ModelMap model) { 

     return "/foo/bar"; 
    } 

} 

或只是一個自定義被重定向到一個視圖,異常(假定控制器中出現new UserNotFound()

public class UserNotFound extends Exception { 
    public UserNotFoundException() { 
     toView(); 
     } 

    public String toView(){ 
    return "/foo/bar"; 
     } 
}