SpringMVC frame (4) - Exception Handling

Exception handling ideas:

The system includes two types of exception: Exception RuntimeException abnormal and is expected to run, in order to gain the former abnormal abnormal information by capturing, which occurs primarily through standardized code development, testing and other means to reduce run-time exception.

System Dao, Service, Controller occurrence throws Exception is thrown up by the last referred to by the front end controller SpringMVC exception handler for exception handling, as shown below:

 

There are two ways to handle exceptions:

① simple exception handler SimpleMappingExceptionResolver Spring MVC offers

Simple exception handler, is springmvc well in advance of the processor interface, configuration can be used directly

<! - Simple Mapping configuration exception handler -> 
<the bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
    <! - default error view -> 
    <Property name = "defaultErrorView" value = "Forward: /error/errorMsg.jsp" />        
    <Property name = "exceptionMappings"> 
        <Map> 
            ! <- zero exception view -> 
            <entry Key = "an ArithmeticException" value = "Forward: / error / Arithmetic .jsp "/>   
            ! <- cast exception view -> 
            <entry Key =" a ClassCastException "value =" Forward: /error/classCast.jsp "/>        
        </ Map> 
    </ Property> 
</ the bean>

② implement Spring exception processing interface HandlerExceptionResolver customize your own exception handler

Define a class that implements an interface HandlerExceptionResolver, override method

public  class MyExceptionResolver the implements the HandlerExceptionResolver { 
    @Override 
    public ModelAndView the resolveException (the HttpServletRequest Request, 
    the HttpServletResponse Response, Object Handler, Exception EX) { 
        // create ModelAndView 
        ModelAndView ModelAndView = new new ModelAndView ();
         // determines what appears abnormal abnormality 
        IF (EX the instanceof an ArithmeticException) {      // If zero exception
             // Go to "Forward: /error/arithmetic.jsp" 
            modelAndView.setViewName ( "Forward: /error/arithmetic.jsp" ); 
        } the else IF (EX the instanceof a ClassCastException) {    // If the type conversion exception 
            modelAndView.setViewName ( "forward: /error/classCast.jsp" ); 
        } the else {   // other abnormality, jump to page exceptionPage 
            modelAndView.setViewName ( "forward: /error/exceptionPage.jsp " ); 
        } 

        return ModelAndView; 
    } 
}

Configuring exception handler

<bean id="exceptionResolver" class="com.itheima.exception.MyExceptionResolver"/>

Guess you like

Origin www.cnblogs.com/j9527/p/12041052.html