SpringMVC core technology-exception handling

The springmvc framework adopts unified, global exception handling, which concentrates all exception handling in the controller into one place, and adopts the idea of aop . Separate business logic and exception handling code.

Steps of exception handling:

        1. Create a custom exception class, and then define its subclass exception

        2. Create a common class as a global exception handling class

                1) Add @ControllerAdvice above the class

                2) Define the method in the class, add @ExpectationHandler above the method

             Handling the thrown exception:

                 @ControllerAdvice: Controller enhancement is to add functions to the controller class (function to handle exceptions)

                 Location: Above the class

                 Features: The framework must know the package name of this annotation, and the component scanner needs to be declared in the springMVC configuration file

                             Specify the location of the package name where @ControllerAdvice is located

                Define class methods to handle exceptions

                          The method of handling exceptions is the same as the definition of the controller method. It can have multiple parameters, and it can have ModelAndView String.. 

                Formal parameter: Exception, which represents the exception object thrown in the Controller

                           The information of the exception can be obtained through the formal parameters

               Annotate the method @ExceptionHandle (class of exception): indicates the type of exception, when such an exception occurs, it will be handled by this method

        3. Throw an exception in the controller

        4. Create a view page that handles exceptions

        5. Create a springmvc configuration file

               1) Component scanner, scan @controller annotation

               2) Component scanner, scan the package name of @ControllerAdvice

               3) Declare annotation driven

Code demo:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="textml; charset=UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="user/some.do" method="post">
        姓名:<input type="text" name="name"><br/>
        年龄:<input type="text" name="age"><br/>
        <input type="submit" value="提交请求">
    </form>
</body>
</html>

Controler class

@RequestMapping(value = "/user")
@Controller
public class myController {
    @RequestMapping(value = "/some.do")
    public ModelAndView dosome(String name,String age) throws myException {
        ModelAndView mv = new ModelAndView();
        //根据请求的参数抛出异常
        if("".equals(name)){
            //抛出的异常交给框架处理
            throw new nameException("姓名不为空");
        }
        if (!isNum(age)) {
            throw  new ageException("年龄输入非数字");
        }
        mv.addObject("myname",name);
        mv.addObject("myage",age);
        mv.setViewName("show");
        return mv;
    }
    public boolean isNum(String str){
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}

Exception class:

public class myException extends Exception {
    public myException() {
        super();
    }
    public myException(String message) {
        super(message);
    }
}
/**
 * 年龄出现异常,抛出异常
 */
public class ageException extends myException {
    public ageException() {
        super();
    }
    public ageException(String message) {
        super(message);
    }
}
/**
 * name出现异常,抛出异常
 */
public class nameException extends myException {
    public nameException() {
        super();
    }
    public nameException(String message) {
        super(message);
    }
}

Handling exceptions thrown

@ControllerAdvice
public class ExceptionHandle {
    @ExceptionHandler(value = nameException.class)
    public ModelAndView doNameException(Exception exception){
        ModelAndView mv  = new ModelAndView();
        mv.addObject("tips","姓名不为空!!");
        mv.addObject("ex",exception);
        mv.setViewName("nameError");
        return mv;
    }
    @ExceptionHandler(value = ageException.class)
    public ModelAndView doAgeException(Exception exception){
        ModelAndView mv  = new ModelAndView();
        mv.addObject("tips","年龄输入错误!!");
        mv.addObject("ex",exception);
        mv.setViewName("ageError");
        return mv;
    }
    //其他的错误信息处理
    @ExceptionHandler
    public ModelAndView doOtherException(Exception exception){
        ModelAndView mv  = new ModelAndView();
        mv.addObject("tips","其他异常错误!!");
        mv.addObject("ex",exception);
        mv.setViewName("otherError");
        return mv;
    }

}

Abnormal display of jsp page: other similarities and minor differences

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ageError.jsp的错误信息<br/>
    ${tips}<br/>
    ${ex.message}<br/>
</body>
</html>

Define the SpringMVC configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <context:component-scan base-package="cn.com.Ycy.Contrller"/>
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 前缀名:视图文件的路径-->
            <property name="prefix" value="/WEB-INF/"/>
            <!-- 后缀名:视图文件的扩展名 -->
            <property name="suffix" value=".jsp"/>
        </bean>
        <!-- 处理异常的两步  -->
        <context:component-scan base-package="cn.com.Ycy.handle"/>
        <mvc:annotation-driven/>
</beans>

 

Guess you like

Origin blog.csdn.net/weixin_43725517/article/details/108253018