SpringMVC 异常处理

来源:互联网 发布:js实现页面搜索功能 编辑:程序博客网 时间:2024/06/06 05:47
1.描述
      在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
     那么,能不能将所有类型的异常处理从各处理过程解耦出来,这样既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护?答案是肯定的。下面将介绍使用Spring MVC统一处理异常的解决和实现过程。

2.分析
Spring MVC处理异常有3种方式:
(1) 使用@ExceptionHandler注解实现异常处理;
(2) 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(3) 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver;

3.使用@ExceptionHandler注解实现异常处理
(1) 页面链接
<a href="${pageContext.request.contextPath}/testExceptionHandlerExceptionResolver?i=1" > testExceptionHandlerExceptionResolver </a >
(2) 控制器方法
package com.atguigu.springmvc.crud.handlers;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;@Controllerpublic class ExceptionHandler {@RequestMapping("/testExceptionHandlerExceptionResolver")public String testExceptionHandlerExceptionResolver(@RequestParam("i") int i){     System.out.println("10/"+i+"="+(10/i));return "success";}}
(3) 测试,出现异常情况:处理异常,跳转到error.jsp

(4) 在控制器中增加处理异常的方法
@ExceprtionHandle(value={java.lang.ArithmeticException.class})     public String handleException(Exception ex,Map<String,Object> map){          System. out.println("出现异常啦L" +ex);           //希望将Exception对象传递给页面,不能使用Map          map.put( "exception",ex);           return "error" ;     }
(5) 增加error.jsp
<h3>Error Page</h3>
     说明1:通过以上map方法,在页面是无法获取错误消息的,如果想要获错误消息,需要使用一下内容;
@ExceptionHandler(value={java.lang.ArithmeticException.class})     public ModelAndView handleException(Exception ex){          System. out.println("出现异常啦L" +ex);           ModelAndView mv = new ModelAndView("error" );          mv.addObject( "exception", ex) ;           return mv;     }
${requestScope.exception }
     说明2:如果想要是的这个异常对所有的异常都起作用,就需要将这些异常提出来到一个类中,然后在类前面加入这个注解:@ControllerAdvice,具体做法如下:
package com.atguigu.springmvc.exhandler;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.servlet.ModelAndView;@ControllerAdvicepublic class ExceptionAdviceHandler {     @ExceptionHandler(value={java.lang.ArithmeticException.class})     public ModelAndView handleException(Exception ex){          System.out.println("出现异常啦"+ex);          ModelAndView mv = new ModelAndView("error");          mv.addObject("exception", ex) ;          return mv;     }     @ExceptionHandler(value={java.lang.RuntimeException.class})     public ModelAndView handleException2(Exception ex){          System.out.println("RuntimeException-出现异常啦:"+ex);          ModelAndView mv = new ModelAndView("error");          mv.addObject("exception", ex);          return mv;     }}
4.实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
(1) 页面链接
< a href ="${pageContext.request.contextPath }/testResponseStatusExceptionResolver?i=10" >testResponseStatusExceptionResolver</a >
(2) 控制器方法
@ResponseStatus(value=HttpStatus.NOT_FOUND,reason="测试方法上设置响应状态码" )  //可有可无     @RequestMapping(value= "/testResponseStatusExceptionResolver" )     public String testResponseStatusExceptionResolver(@RequestParam ("i" ) int i){           if(i==13){               throw new UsernameNotMatchPasswordException();          }          System. out.println("testResponseStatusExceptionResolver..." );          return "success" ;     }
(3) 自定义异常类
package com.atguigu.springmvc.exception;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.ResponseStatus;@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户名称和密码不匹配")public class UsernameNotMatchPasswordException extends RuntimeException {}
5.使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
     如果希望对所有异常进行统一处理,可以使用 SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常。
(1) 增加页面链接
<a href="testSimpleMappingExceptionResolver?i=12">testSimpleMappingExceptionResolver</a>
(2) 增加控制器方法
@RequestMapping("/testSimpleMappingExceptionResolver")public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){     System.out.println("testSimpleMappingExceptionResolver...");     String[] s = new String[10];     System.out.println(s[i]);     return "success";}
(3) 出现异常情况:参数i的值大于10

(4) 配置异常解析器:自动将异常对象信息,存放到request范围内
<!-- 配置SimpleMappingExceptionResolver异常解析器 --><bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><!-- exceptionAttribute默认值(通过ModelAndView传递给页面):exception   ->  ${requestScope.exception}public static final String DEFAULT_EXCEPTION_ATTRIBUTE = "exception";--><property name="exceptionAttribute" value="exception"></property><property name="exceptionMappings"><props><prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop></props></property></bean>
      error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h3>Error Page</h3>     ${exception }     ${requestScope.exception }</body></html>

原创粉丝点击