Do you know these details about SpringMVC's exception handling?

foreword

Hello everyone, I am Brother Qianfengwen. Today, Brother Wen will explain to you how to handle exceptions in SpringMVC. In WEB applications, if an exception occurs inside the program, if we do not handle it, the exception information will be directly thrown to the browser page, resulting in a very poor user experience. For users, this is very unfriendly, so we must deal with the exception information thrown by the application. Today, Brother Wen will explain to you how SpringMVC handles exceptions. Regarding the exception handling method, Brother Wen divides it into two types for everyone, one is the default exception handling method of SpringMVC, and the other is other exception handling methods supported by SpringMVC.

SpringMVC default exception handling method

The default exception handling method of SpringMVC is the same as the way Servlet handles exceptions. We only need to define the exception handling configuration in web.xml. Now Brother Wen will show you how to implement the default exception handling in SpringMVC.

1. Create a web project and build a SpringMVC environment

Now we use maven to create a web project, then introduce dependencies and configure the SpringMVC environment. I believe that the friends are very proficient in this part of the operation, so Brother Wen will not repeat it. After we set up the basic environment of SpringMVC, we started to perform the following operations.

Step 1: Write a target page that jumps successfully, which we define as success.jsp.

In an ideal situation, if there is no exception in our program, then the target page of the jump is success.jsp.

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <h4>这是一个成功页面.....</h4>
</body>
</html>

Step Two: Write the Controller Code

Next, we write the Controller code. Inside the controller method, we define the code that simulates the abnormality of the program. The specific code is defined as follows:

@Controller
@RequestMapping("hello")
public class HelloController {
    @RequestMapping("demo1")
    public String demo1(String username){
              int i = 10 / 0; //模拟异常出现的代码
        System.out.println("demo1方法执行了......");
        return "success";
}

When we started the project and sent a request, we found that the exception information was thrown on the browser page, which was very unfriendly.

picture

So we need to deal with the abnormal information that appears, how to deal with it? We define the configuration information for handling errors in web.xml.

2. Configure exception handling rules

In web.xml, we define exception handling rules as follows:

<error-page>
  <error-code>500</error-code>
  <location>/500.jsp</location>
</error-page>

<error-page>
  <error-code>404</error-code>
  <location>/404.jsp</location>
</error-page>

We define the exception status code and page for handling exceptions in the error-page tag. If a 500 error occurs inside our server, we will jump to the 500.jsp page for exception handling; if the requested resource cannot be found, then we will jump to 404.jsp for exception handling. In this way, the exception information is no longer directly thrown to the browser page. Now we define the jsp pages for these two kinds of error handling respectively.

3. Define the error handling page

First, we define the 404.jsp page under the webapps directory. The page definition is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <h4>服务器资源不存在.....</h4>
</body>
</html>

Next, we define the 500.jsp page under the webapps directory. The page definition is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
   <h4>这是一个500错误,请稍后再试.....</h4>
</body>
</html>

Now we restart the project, resend the request, and check whether the exception information is processed successfully:

picture

Next, let's simulate a 400 exception handling request, let's see if the 400 type exception can be handled successfully:

picture

The above are the rules for Servlet to handle exceptions by default. In SpringMVC, this way of handling exceptions is also applicable. Do you guys think it is very simple!

SpringMVC other exception handling methods

In addition to the default exception handling methods, SpringMVC also supports other exception handling methods. Next, Brother Wen will show you the other exception handling methods supported by SpringMVC.

1. @ControllerAdvice + @ExceptionHandler annotation for exception handling

Now Brother Wen will show you the specific steps of using @ControllerAdvice + @ExceptionHandler annotations for exception handling.

Step 1: Write the controller method

We write several controller methods to simulate different types of exceptions inside the controller method. The specific definition method is as follows:

@Controller
@RequestMapping("exception")
public class ExceptionController {

    //模拟出现空指针异常
    @RequestMapping("testException")
    public String testException(){
        int[] arr = null;
        arr[100] = 101;
        return "success";
    }

    //模拟数组下标越界异常
    @RequestMapping("testException1")
    public String testException1(){
        int[] arr = new int[3];
        arr[5] = 100;
        return "success";
    }

    //模拟除0异常
    @RequestMapping("testException2")
    public String testException2(){
        int i = 10 / 0;
        System.out.println(i);
        return "success";
    }
}

Step 2: Write exception handling class

Now we write a class that is decorated with @ControllerAdvice annotation. In this class, we define error handling methods for different exception types, which are decorated with @ExceptionHandler annotations.

/**
 * 标识当前类是一个异常处理类
 */
@ControllerAdvice
public class MVCExceptionHandler {

    /**
     * 处理空指针异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = {NullPointerException.class})
    public ModelAndView nullPointerExceptionHandler(Exception e){
        ModelAndView modelAndView = new ModelAndView();
        //描述异常信息
        modelAndView.addObject("msg",e.toString());
        //设置异常处理视图
        modelAndView.setViewName("error");
        return modelAndView;
    }

    /**
     * 处理算术异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ArithmeticException.class)
    public ModelAndView arithmeticExceptionHandler(Exception e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",e.toString());
        modelAndView.setViewName("error");
        return modelAndView;
    }

    /**
     * 处理下标越界异常
     * @param ex
     * @return
     */
    @ExceptionHandler(value = ArrayIndexOutOfBoundsException.class)
    public ModelAndView arrayIndexOutOfBoundsExceptionHandler(Exception ex){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",ex.toString());
        modelAndView.setViewName("error");
        return modelAndView;
    }

}

We found that in the current exception handling class, the logic we define to handle exceptions is to return the ModelAndView object. Through the ModelAndView object, we set the page that handles exceptions to be the error.jsp page. Next we define the error handling page.

Step 3: Write an exception handling page

Under the webapps directory, we define an error handling page, the page name is error.jsp, and the definition is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h4>这是一个错误处理页面......</h4>
    <span>${msg}</span>
</body>
</html>

Step 4: Start the project and test the effect

Next, we start the project, send a request, and check the test results.

picture

2. Use SimpleMappingExceptionResolver to handle global exceptions

We can also use the SimpleMappingExceptionResolver component to help us handle exceptions globally, provided that we need to inject the SimpleMappingExceptionResolver component into the Spring container. Next, Brother Wen will show you how SimpleMappingExceptionResolver handles exceptions.

Step 1: Define a configuration class and hand SimpleMappingExceptionResolver to Spring container management

Now we define a Java configuration class, and then define a method. We use the @Bean annotation to modify this method, and the return value type of the method is the SimpleMappingExceptionResolver type. The component is handed over to the Spring container for management by configuring the class.

/**
 * 全局异常处理器
 */
@Configuration
public class GlobalExceptionHandler {

    @Bean
    public SimpleMappingExceptionResolver getExceptionResolver(){
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties properties = new Properties();
        /**
         * 参数1:处理的具体的异常的类型
         * 参数2:处理异常需要跳转到的视图
         */
        properties.put("java.lang.NullPointerException","error");
        properties.put("java.lang.ArithmeticException","error");
        properties.put("java.lang.ArrayIndexOutOfBoundsException","error");
        resolver.setExceptionMappings(properties);
        return resolver;
    }
}

Step 2: Define the jsp page that handles the exception

Under the webapps directory, we define an error handling page, the page name is error.jsp, and the definition is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h4>这是一个错误处理页面......</h4>
</body>
</html>

Step 3: Start the project and test the effect

Next, we start the project, send a request, and check the test results.

picture

3. Custom exception handler

In SpringMVC, we also support our custom components. At the bottom of SpringMVC, Spring officially customized many exception handlers for us. If none of these exception handlers meet our needs, we can also customize exception handlers to help us handle exceptions. Next, Brother Wen will show you how to implement a custom exception handler:

Step 1: Define a class that implements the HandlerExceptionResolver interface

Now we define a global exception handling class. We need to implement the HandlerExceptionResolver interface for this class. There is a method resolveException in this interface. This method is the method that provides us with the definition of exception handling information.

/**
 * 异常处理器  必须实现HandlerExceptionResolver接口
 */
@Component
public class ExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse, 
                                         Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",e.toString());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

Step 2: Define the jsp page that handles the exception

Under the webapps directory, we define an error handling page, the page name is error.jsp, and the definition is as follows:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h4>这是一个错误处理页面......</h4>
</body>
</html>

Step 3: Start the project and test the effect

Next, we start the project, send a request, and check the test results.

Summarize

Through this article, Brother Wen demonstrated to you how to handle exceptions in SpringMVC. Through the study of this article, friends should have discovered that in SpringMVC, SpringMVC provides us with a variety of exception handling methods, and each exception handling method is supported by a corresponding exception handler at the bottom of SpringMVC. 0-based friends, we first need to learn how to use it. In the next article, Brother Wen will explain how to use interceptors in SpringMVC, so please look forward to it!

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/132359737