• SpringMVC(三)异常处理


    一、在Controller内处理局部异常
     
         @ExceptionHandler(value={ArithmeticException.class})
    	public ModelAndView handlExecution(Exception ex){
             ModelAndView  mView=new ModelAndView();
             mView.setViewName("error");
             mView.addObject("exception",ex);
             System.out.println("Controller内部异常处理");
             return mView;
    	}
    	@RequestMapping("/testExection")
    	public String testExection(@RequestParam(value="id") Integer id){
    		System.out.println(10/id);
    		return "success";
    	}
    

    二、处理全局异常---------定义一个异常处理了
    package com.neuedu.springmvc.execption;
    
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    /* 
    * 项目名称:springmvc-03 
    * @author:wzc
    * @date 创建时间:2017年8月24日 下午3:31:09
    * @Description:处理全局异常的类
    * @parameter  
    *   */
    @ControllerAdvice
    public class MyExcption {
    	@ExceptionHandler(value={ArithmeticException.class})
    	public String handlExecution(Exception ex){
    		return "error";
    	}
    }
    

    条件:
    1.加上<mvc:annotation-driven>标签:
    2.在当前Handler中定义由@ExceptionHandler注解修饰的方法,用于处理异常信息!
    注意:
    1.@ExceptionHandler方法修饰的入参中可以加入Exception类型的参数,该参数即对应发生的异常信息
    2.@ExceptionHandler方法的入参中不能传入Map.若希望把异常信息传到页面上,需要使用ModelAndView作为方法的返回值。
    3.@ExceptionHandler 注解定义的方法优先级问题:
    例如发生的是NullPointerException,但是声明的异常有 RuntimeException 和 Exception,
    此候会根据异常的最近 继承关系找到继承深度最浅的那个 @ExceptionHandler 注解方法,即标记了 RuntimeException 的方法
    4.ExceptionHandlerMethodResolver 内部若找不 到@ExceptionHandler 注解的话,会找@ControllerAdvice 中的@ExceptionHandler 注解方法
     

    三、在配置中配置异常处理
     
    <!-- 配置异常处理 -->
    <!-- 配置异常处理 -->
      <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
      		<props>
      		  <!-- 处理的错误异常类型,以及跳转的页面 -->
      		   <prop key="java.lang.ArithmeticException">error</prop>
      		</props>
      </property>
      </bean>
    
  • 相关阅读:
    Getting started with the Web ADF
    将搜狗浏览器设置为IIS的默认浏览器
    What is installed with the Web ADF?
    如何修改Flex的默认浏览器
    What is the Web Application Developer Framework
    windows C++获得本地IP地址
    lua table函数库
    【铸铁】C++服务器面试题.doc
    VC2008下提示找不到MSVCP90D.dll的解决办法
    排序
  • 原文地址:https://www.cnblogs.com/Actexpler-S/p/7424800.html
Copyright © 2020-2023  润新知