1.
@ExceptionHandler(ArithmeticException.class)
public ModelAndView getArithmeticException(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("ex", ex);
return mv;
}
@RequestMapping("/zero")
public void ac(@RequestParam("i") int i){
System.out.println(10/i);
}
當發生ArithmeticException異常的時候,在error.jsp頁面輸出異常 。
2.
@ControllerAdvice
public class Exceptions {
@ExceptionHandler(ArithmeticException.class)
public ModelAndView getArithmeticException(Exception ex){
ModelAndView mv = new ModelAndView("error");
mv.addObject("ex", ex);
return mv;
}
}
如果在本類中找不到異常處理的方法,就去@ControllerAdvice注解的類中查找異常處理的類的方法。
3.
@ResponseStatus(value=HttpStatus.BAD_REQUEST,reason="請求不對")
public class UserExceptions extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
}
在controller的方法里拋出UserExceptions 異常,在頁面上顯示
HTTP Status 400 - 請求不對