SpringMVC 异常处理机制

SpringMVC 异常处理机制_第1张图片

异常处理两种方式:

一、使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

直接在spring-mvc.xml中进行配置:

    
    
        
        
            
                
                
            
        
    

 二、自定义异常处理器

  1、通过实现HandlerExceptionResolver自定义异常处理器:

public class MyExceptionResolver implements HandlerExceptionResolver {

    /*
        参数Exception:异常对象
        返回值ModelAndView:跳转到错误视图信息
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();

        if(e instanceof 自定义异常){
            modelAndView.addObject("info","自定义异常");
        }else if(e instanceof ClassCastException){
            modelAndView.addObject("info","类转换异常");
        }

        modelAndView.setViewName("error.jsp");

        return modelAndView;
    }
}

  2、在spring-mvc.xml中配置异常处理器:

    
    

  3、编写异常页面error.jsp...

  4、测试异常跳转:

@Controller
public class exceptionController {
    @Autowired
    private 各种异常 exce;

    @RequestMapping(value = "/V")
    public String show() throws FileNotFoundException, 自定义异常 {
        System.out.println("show running......");
        exce.ex1();
        //exce.ex2();
        //exce.ex3();
        //exce.ex4();
        //exce.ex5();
        return "index.jsp";
    }
}

你可能感兴趣的:(高级框架,spring)