Loading

SpringMVC异常处理

步骤

  1. 新建一个自定义异常类UserException,再定义它的子类NameException和AgeException.
public class AgeException extends UserException{
    public AgeException() {
    }

    public AgeException(String message) {
        super(message);
    }
}

public class NameException extends UserException{
    public NameException() {
    }

    public NameException(String message) {
        super(message);
    }
}

public class UserException extends Exception{
    public UserException() {
    }

    public UserException(String message) {
        super(message);
    }
}

  1. 再controller中抛出NameException,AgeException。
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/some")
    public ModelAndView doSome(String name,Integer age) throws UserException {
        ModelAndView modelAndView = new ModelAndView();
        if(!name.equals("黄振聪")){
            throw new NameException("用户:"+name+"不是黄振聪!");
        }
        if(age == null || age > 100){
            throw new AgeException("年龄不符合要求!");
        }
        modelAndView.addObject("uname",name);
        modelAndView.addObject("uage",age);
        modelAndView.setViewName("target");
        return modelAndView;
    }
}
  1. 创建一个普通类,作为全局异常处理类。并在类的上面加上@ControllerAdvice,在类中定义方法,方法上面加入@ExceptionHandler.
@ControllerAdvice
public class UserExceptionHandler {
    /**
     @ExceptionHandler: 
        属性:
            value:指定异常类,若没有指定则表示其他所有异常
     */
    @ExceptionHandler(value = NameException.class)
    public ModelAndView nameException(Exception ex){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("tips","处理NameException");
        modelAndView.addObject("ex",ex);
        modelAndView.setViewName("nameError");
        return modelAndView;
    }
    @ExceptionHandler(value = AgeException.class)
    public ModelAndView ageException(Exception ex){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("tips","处理AgeException");
        modelAndView.addObject("ex",ex);
        modelAndView.setViewName("ageError");
        return modelAndView;
    }
    @ExceptionHandler
    public ModelAndView otherException(Exception ex){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("ex",ex);
        modelAndView.setViewName("otherError");
        return modelAndView;
    }
}
  1. 创建处理异常的视图界面。
  2. 在SpringMVC配置文件中添加:组件扫描器,扫描@Controller注解和@ControllerAdvice所在的包名;声明注解驱动。
    <context:component-scan base-package="com.hzc.controller" />
    <context:component-scan base-package="com.hzc.handler" />
    <mvc:annotation-driven />

结构图:

posted @ 2021-08-22 05:34  IamHzc  阅读(40)  评论(0编辑  收藏  举报