SpringMVC配置异常处理

SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver

SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver

配置异常处理两种方式:

xml配置、注解配置

以下为代码演示:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>错误</title>
</head>
<body>
<h1>error.html</h1>
<p th:text="${ex}"></p>
</body>
</html>
package com.qcw.controller;

@Controller
public class TestController {
    
    

    @RequestMapping("/test/hello")
    public String testHello(){
    
    
        System.out.println(1/0);
        return "success";
    }
}

1.xml方式

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!--key设置要处理的异常,value设置出现该异常时要跳转的页面所对应的逻辑视图-->
                <prop key="java.lang.ArithmeticException">error</prop>
            </props>
        </property>
        <!--设置共享在请求域中的异常信息的属性名-->
        <property name="exceptionAttribute" value="ex"></property>
    </bean>

2.注解方式

package com.qcw.controller;

//将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
    
    

    //设置要处理的异常信息
    @ExceptionHandler(ArithmeticException.class)
    public String handleException(Throwable ex, Model model){
    
    
        //ex标识控制器方法所出现的异常
        model.addAttribute("ex",ex);
        return "error";
    }
}

猜你喜欢

转载自blog.csdn.net/qq_47637405/article/details/127159318
今日推荐