SpingMVC-异常处理

SpingMVC

异常处理_ExceptionHandler注解

  • 在这里插入图片描述

  • 在这里插入图片描述

  • 测试

    • 先在SpringMVCTest.java中新建一个测试方法

      @RequestMapping("/testExceptionHandlerExceptionResolver")
      	public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){
      		System.out.println("result: " + (10 / i));
      		return "success";
      	}
      
    • 再在index.jsp中新建一个超链接

      <a href="testExceptionHandlerExceptionResolver?i=10">Test ExceptionHandlerExceptionResolver</a>

    • 在SpringMVCTest.java中写两个出异常的方法

      	@ExceptionHandler({RuntimeException.class})
      	public ModelAndView handleArithmeticException2(Exception ex){
      	System.out.println("[出异常了]: " + ex);
      		ModelAndView mv = new ModelAndView("error");
      		mv.addObject("exception", ex);
      		return mv;
      	}
      	
      	/**
      	 * 1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
      	 * 2. @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 需要使用 ModelAndView 作为返回值
      	 * 3. @ExceptionHandler 方法标记的异常有优先级的问题.  会查找最接近这个异常的方法
      	 * 4. @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常, 
      	 * 则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常. 
      	 */
      	@ExceptionHandler({ArithmeticException.class})
      	public ModelAndView handleArithmeticException(Exception ex){
      		System.out.println("出异常了: " + ex);
      		ModelAndView mv = new ModelAndView("error");
      		mv.addObject("exception", ex);
      		return mv;
      	}
      
    • 当修改testExceptionHandlerExceptionResolver超链接的i为0时,触发数学异常会执行精确度最高的@ExceptionHandler({ArithmeticException.class})这个异常

      页面效果

      在这里插入图片描述

  • @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常,
    则将去 @ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常.

    • 测试时 要先把SpringMVCTest.java的那两个异常方法注掉

      • 在com.atguigu.springmvc.test包下新建一个SpringMVCTestExceptionHandler.java类

        import org.springframework.web.bind.annotation.ControllerAdvice;
        import org.springframework.web.bind.annotation.ExceptionHandler;
        import org.springframework.web.servlet.ModelAndView;
        
        @ControllerAdvice
        public class SpringMVCTestExceptionHandler {
        
        	@ExceptionHandler({ArithmeticException.class})
        	public ModelAndView handleArithmeticException(Exception ex){
        		System.out.println("----> 出异常了: " + ex);
        		ModelAndView mv = new ModelAndView("error");
        		mv.addObject("exception", ex);
        		return mv;
        	}
        	
        }
        

异常处理_ResponseStatusExceptionResolver

  • 测试

    • @ResponseStatus加到类上

      • 在com.atguigu.springmvc.test包下新建一个UserNameNotMatchPasswordException.java类(自定义一个异常)

        package com.atguigu.springmvc.test;
        
        import org.springframework.http.HttpStatus;
        import org.springframework.web.bind.annotation.ResponseStatus;
        /*
         * value=HttpStatus.FORBIDDEN这个是状态码403 reason="用户名和密码不匹配!":原因
         */
        @ResponseStatus(value=HttpStatus.FORBIDDEN, reason="用户名和密码不匹配!")
        public class UserNameNotMatchPasswordException extends RuntimeException{
        
        	/**
        	 * 
        	 */
        	private static final long serialVersionUID = 1L;
        
        	
        }
        
      • 在SpringMVCTest.java下新建一个测试方法

        @RequestMapping("/testResponseStatusExceptionResolver")
        	public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
        		if(i == 13){
        			throw new UserNameNotMatchPasswordException();
        		}
        		System.out.println("testResponseStatusExceptionResolver...");
        		
        		return "success";
        	}
        
      • 在index.jsp中建立一个对应的超链接

        <a href="testResponseStatusExceptionResolver?i=10">Test ResponseStatusExceptionResolver</a>

        点击超链接并把i改为13,则触发我们自定义的异常

        在这里插入图片描述

    • @ResponseStatus加到方法上

      	@ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND)
      	@RequestMapping("/testResponseStatusExceptionResolver")
      	public String testResponseStatusExceptionResolver(@RequestParam("i") int i){
      		if(i == 13){
      			throw new UserNameNotMatchPasswordException();
      		}
      		System.out.println("testResponseStatusExceptionResolver...");
      		
      		return "success";
      	}
      

      这时无论超链接上的i改为多少 都会弹出异常页面,但是打印是正常的

      在这里插入图片描述

异常处理_DefaultHandlerExceptionResolver

  • 在这里插入图片描述

  • 测试

    • 在SpringMVCTest.java下新建一个方法

      @RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
      	public String testDefaultHandlerExceptionResolver(){
      		System.out.println("testDefaultHandlerExceptionResolver...");
      		return "success";
      	}
      
    • 在index.jsp中加入一个超链接

      <a href="testDefaultHandlerExceptionResolver">Test DefaultHandlerExceptionResolver</a>

    • 这时点击此超链接就会触发异常,因为点击超链接是get请求,但是@RequestMapping注解里只让post请求访问

      在这里插入图片描述

异常处理_SimpleMappingExceptionResolver

  • 在这里插入图片描述

  • 在SpringMVCTest.java里建一个目标方法

    • @RequestMapping("/testSimpleMappingExceptionResolver")
      	public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
      		String [] vals = new String[10];
      		System.out.println(vals[i]);
      		return "success";
      	}
      
  • 在springmvc.xml中配置出异常时转向哪个页面

    • <!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
      	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      		<property name="exceptionAttribute" value="ex"></property>
      		<!-- exceptionAttribute是异常的属性名 value="ex"也就是把我们用的exception改为ex 比如${requestScope.exception }就可以改为${requestScope.ex }   -->
              <property name="exceptionMappings">
      			<props>
                      <!--配置出现数组越界异常转向的页面-->
      				<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
      			</props>
      		</property>
      	</bean>	
      
  • 在index.jsp中加入对应的超链接

    <a href="testSimpleMappingExceptionResolver?i=2">Test SimpleMappingExceptionResolver</a>

    点击超链接后,把超链接上的i改为20(方法中数组范围是10)所以越界了出现异常

    因为xml文件中配置了出现数组越界异常转向的error页面,所以页面转向error页面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值