Home >Java >javaTutorial >springMVC support for exception handling

springMVC support for exception handling

巴扎黑
巴扎黑Original
2017-06-26 09:21:201323browse

No matter what project you are doing, exception handling is very necessary, and you cannot throw some error codes that only programmers can understand to users, so at this time, perform unified exception handling to show a comparison Friendly error pages are necessary. Like other MVC frameworks, springMVC also has its own exception handling mechanism.
There are two main ways to handle exceptions provided by springMVC. One is to directly implement your own HandlerExceptionResolver. Of course, this also includes using the SimpleMappingExceptionResolver and DefaultHandlerExceptionResolver that Spring has provided us. The other is to use annotations to implement a specialized Controller for handling exceptions - ExceptionHandler.

1. Implement your own HandlerExceptionResolver. HandlerExceptionResolver is an interface. springMVC itself already has its own implementation-DefaultHandlerExceptionResolver. This resolver is just for Some of the more typical exceptions are intercepted and then the corresponding error codes are returned. Of course, you can also inherit the DefaultHandlerExceptionResolver class and then rewrite some of the exception handling methods to implement your own exception handling.

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.springframework.web.servlet.HandlerExceptionResolver;  
import org.springframework.web.servlet.ModelAndView;  
  
public class ExceptionHandler implements HandlerExceptionResolver {  
  
    @Override  public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex) {  // TODO Auto-generated method stub  return new ModelAndView("exception");  
    }  
  
}

The fourth of the above resolveException The parameter indicates which type of exception is handled. Because the Exception class is the base class of all exception classes, if you want to perform different processing according to different exception types, you can perform different processing according to different exception types in the resolveException method and return different exception views. For example:

public class ExceptionHandler implements HandlerExceptionResolver {  
  
    @Override  public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex) {  // TODO Auto-generated method stub  if (ex instanceof NumberFormatException) {  //doSomething...  return new ModelAndView("number");  
        } else if (ex instanceof NullPointerException) {  //doSomething...  return new ModelAndView("null");  
        }  return new ModelAndView("exception");  
    }  
  
}

After defining such an exception handler, you must define such a bean object in the applicationContext, such as:

bean id="exceptionResolver" class="com.tiantian.xxx.web.handler.ExceptionHandler"/> ;
##In addition to implementing a DefaultHandlerExceptionResolver, Spring also implements a SimpleMappingExceptionResolver, which Both inherit from the abstract class AbstractHandlerExceptionResolver, and AbstractHandlerExceptionResolver implements the resolveException method of the HandlerExceptionResolver interface, and thus extracts two abstract methods, one is the method prepareResponse (exception, response) that is executed before exception handling, and the other is It is the doResolveException(request, response, handler, exception) method for exception resolution. SimpleMappingExceptionResolver, as its name implies, uses a simple mapping relationship to determine which view should handle the current error message. SimpleMappingExceptionResolver provides the mapping relationship between exceptions and views through exception type exceptionMappings, and provides statusCodes to map the view name returned by the exception and the corresponding HttpServletResponse return code when an exception occurs. And the default value can be specified through defaultErrorView and defaultErrorCode. defaultErrorView means that when the corresponding exception type is not found in exceptionMappings, the view defined by defaultErrorView will be returned. defaultErrorCode means that when an exception occurs, it will not be found in statusCodes, the mapping relationship between the view and the return code. The corresponding mapping is the return code returned by default. When using SimpleMappingExceptionResolver, when an exception occurs, SimpleMappingExceptionResolver will put the current exception object into its own attribute exceptionAttribute. When exceptionAttribute is not specified, exceptionAttribute uses the default value exception.

The following is a simple example:

(1) Declare a SimpleMappingExceptionResolver bean in the SpringMVC servlet configuration file, and configure the attribute exceptionMappings and defaultExceptionView to specify the corresponding relationship between exceptions and views

Xml代码
<bean>  
    <property>  
        <props>  
            <prop>number</prop><!-- 表示当抛出NumberFormatException的时候就返回名叫number的视图 -->  
            <prop>null</prop>  
        </props>  
    </property>  
    <property></property><!-- 表示当抛出异常但没有在exceptionMappings里面找到对应的异常时 返回名叫exception的视图-->  
    <property><!-- 定义在发生异常时视图跟返回码的对应关系 -->  
        <props>  
            <prop>500</prop><!-- 表示在发生NumberFormatException时返回视图number,然后这里定义发生异常时视图number对应的HttpServletResponse的返回码是500 -->  
            <prop>503</prop>  
        </props>  
    </property>  
    <property></property><!-- 表示在发生异常时默认的HttpServletResponse的返回码是多少,默认是200 -->  
</bean>
(2 )Access as follows:

@Controller  
@RequestMapping("/test")  
public class TestController {  
  
    @RequestMapping("/null")  public void testNullPointerException() {  
        Blog blog = null;  //这里就会发生空指针异常,然后就会返回定义在SpringMVC配置文件中的null视图          System.out.println(blog.getId());  
    }  
      
    @RequestMapping("/number")  public void testNumberFormatException() {  //这里就会发生NumberFormatException,然后就会返回定义在SpringMVC配置文件中的number视图  Integer.parseInt("abc");  
    }  
      
    @RequestMapping("/default")  public void testDefaultException() {  if (1==1)  //由于该异常类型在SpringMVC的配置文件中没有指定,所以就会返回默认的exception视图  throw new RuntimeException("Error!");  
    }  
      
}

(3) The exception object that can be accessed in the Jsp page, here is the return view number.jsp of NumberFormatException as an example:

Jsp code
springMVC support for exception handling
  
  
  
nbsp;HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  
    
    <base>">  
      
    <title>My JSP 'number.jsp' starting page</title>  
      
    <meta>  
    <meta>  
    <meta>      
    <meta>  
    <meta>  
    <!--  
    <link rel="stylesheet" type="text/css" href="styles.css?1.1.11">  
    -->  
  
    
    
    
    NumberFormatException. <br>  
    <br>  
    <br><span><!-- 这是JSP中的内置对象exception --></span>  
  
  
  
    <br><span><!-- 这是SpringMVC放在返回的Model中的异常对象 --></span>  
  
  
  
    <span><!-- HttpServletResponse返回的错误码信息,因为前面已经配置了NumberFormatException的错误码返回值为888,所以这里应该显示888 --></span>  
  
  
  
    

(4)当请求/test/number.do的时候会返回定义好的number视图,返回结果如下:


 

2、使用@ExceptionHandler进行处理

 

使用@ExceptionHandler进行处理有一个不好的地方是进行异常处理的方法必须与出错的方法在同一个Controller里面

 

如:

Java代码  springMVC support for exception handling
 
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.ExceptionHandler;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
import com.tiantian.blog.web.servlet.MyException;  
  
@Controller  
public class GlobalController {  
  
      /** 
     * 用于处理异常的 
     * @return 
     */  
    @ExceptionHandler({MyException.class})  public String exception(MyException e) {  
        System.out.println(e.getMessage());  
        e.printStackTrace();  return "exception";  
    }  
      
    @RequestMapping("test")  public void test() {  throw new MyException("出错了!");  
    }  
      
      
}

 

这里在页面上访问test方法的时候就会报错,而拥有该test方法的Controller又拥有一个处理该异常的方法,这个时候处理异常的方法就会被调用

 

 

优先级

既然在SpringMVC中有两种处理异常的方式,那么就存在一个优先级的问题:

 

当发生异常的时候,SpringMVC会如下处理:

(1)SpringMVC会先从配置文件找异常解析器HandlerExceptionResolver

(2)如果找到了异常异常解析器,那么接下来就会判断该异常解析器能否处理当前发生的异常

(3)如果可以处理的话,那么就进行处理,然后给前台返回对应的异常视图

(4)如果没有找到对应的异常解析器或者是找到的异常解析器不能处理当前的异常的时候,就看当前的Controller中有没有提供对应的异常处理器,如果提供了就由Controller自己进行处理并返回对应的视图

(5)如果配置文件里面没有定义对应的异常解析器,而当前Controller中也没有定义的话,那么该异常就会被抛出来。

The above is the detailed content of springMVC support for exception handling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn