这是对视图层出现异常的管理,也就是只有controller发生的异常才能对其管理
1.自定义异常类:
// 年龄异常
public class UserAgeException extends Exception{
public UserAgeException() {
super();
}
public UserAgeException(String message) {
super(message);
}
}
// 性别异常
public class UserSexException extends Exception {
public UserSexException() {
super();
}
public UserSexException(String message) {
super(message);
}
}
2.在具体的视图处理器上加上逻辑,监测异常
if (user.getAge()>100){
throw new UserAgeException();
}
if (!user.getSex().equals("男")&&!user.getSex().equals("女")){
throw new UserSexException();
}
3.定义一个处理全局异常的类,在类上加上@ControllerAdvice注解,在里面的每个方法上加上 @ExceptionHandler(value = ‘自定义的异常类’.class),这样,当springmvc容器里发生异常后,都会到这里处理
@ControllerAdvice
public class GlobalException {
@ExceptionHandler(value = UserAgeException.class)
public ModelAndView ageExceptionHander(){
// System.out.println("年龄错了");
ModelAndView mv = new ModelAndView();
mv.addObject("msg","年龄错误");
mv.setViewName("ageException");
return mv;
}
@ExceptionHandler(value = UserSexException.class)
public ModelAndView sexExceptionHander(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","性别错误");
mv.setViewName("ageException");
return mv;
}
@ExceptionHandler
public ModelAndView doOtherException(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","其他异常");
mv.setViewName("otherException");
return mv;
}
}
最后,在springmvc加上配置文件,确保能够创建这些对象
<mvc:annotation-driven/>
<context:component-scan base-package="com.ls.hander"/>