Spring MVC 全局异常处理

一、实现 HandlerExceptionResolver 接口

public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", e.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

二、创建 Spring MVC 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 配置创建 Spring 容器要扫描的包 -->
    <context:component-scan base-package="chu.yi.bo">
        <!-- 制定扫包规则 ,只扫描使用 @Controller 注解的 JAVA 类 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 配置自定义异常处理器 -->
    <bean id="handlerExceptionResolver" class="chu.yi.bo.CustomExceptionResolver"/>

    <!-- 加载处理映射器和处理适配器 -->
    <mvc:annotation-driven/>

</beans>

三、配置 web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <servlet>
    <!-- 配置 Spring MVC 核心控制器 -->
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <!-- 配置 Spring MVC 核心控制器的参数,读取 Spring MVC 配置文件 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:SpringMVC.xml</param-value>
    </init-param>
  </servlet>

  <!-- 配置 Spring MVC 核心控制器拦截哪些请求 URL -->
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

四、创建 Controller 测试

@Controller("customExceptionController")
public class CustomExceptionController {

    @RequestMapping("/customException")
    public String testCustomException() {
        int i = 1 / 0;
        return "success";
    }
}
发布了34 篇原创文章 · 获赞 0 · 访问量 897

猜你喜欢

转载自blog.csdn.net/u010723080/article/details/104378980