文章目录

  • 概念
  • SpringMVC的异常处理机制
  • 一、创建相关的类
  • 二、创建配置文件
  • 三、部署
  • 四、使用


概念

系统中的异常分为两种:

  • 预期异常:通过try-catch来捕获异常或者抛出异常;
  • 运行时异常:RuntimeException,通过测试来检测;

再mvc模式中,我们一般需要把dao层、service层、Controller层的异常一层一层往上抛,最后由前端控制器交由异常处理器处理;

SpringMVC提供全局的异常处理器,一个系统中只存在一个处理器;

自定义异常类:
自定义异常类需要继承Exception类,针对预期异常进行处理;

全局异常处理器处理思路:
对异常进行分析,如果是自定义的异常,直接取出信息,在错误页面显示,如果不是系统自定义的类型,构造一个异常类型,给它特定的标识;

SpringMVC提供了一个异常接口,需要实现HandlerExceptionResolver接口里面的方法;

SpringMVC的异常处理机制

步骤:

  1. 创建相关的类;
  2. 创建相关的配置文件;
  3. 部署;
  4. 使用;

一、创建相关的类

springsecurity异常处理机制 springmvc的异常处理机制_spring


自定义一个异常类CsException:

public class CsException extends Exception{
    private String message;  //记录异常信息

    public CsException(String message) {
        super(message);
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

自定义一个全局异常处理器类CostomException:

public class CostomException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        CsException csException;
        if(e instanceof CsException) {
            //自定义的异常类
            csException = (CsException)e;
        }else {
            //未识别的异常
            csException = new CsException("未知类型异常");
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message",csException.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

创建一个Controller类用来测试:

@Controller
public class TestController {
    @RequestMapping("/xxx")
    public void getXXX() throws CsException {
        try {
            int a = 45/0;
        }catch (Exception e) {
            throw new CsException("分母不能为0!!");
        }
    }
}

二、创建配置文件

springsecurity异常处理机制 springmvc的异常处理机制_spring_02


创建spring.xml:

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--开启注解扫描-->
    <context:component-scan base-package="com.tulun8"/>

    <!--异常处理器-->
    <bean class="com.tulun8.exception.CostomException"/>
</beans>

创建SpringMVC的配置文件spring-mvc.xml:

<?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="com.tulun8.controller"/>

    <!--自动扫描mvc相关的注解 适配器、映射器等,都有相关的默认配置-->
    <mvc:annotation-driven/>

    <!--视图处理器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置jsp的视图解析类-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

错误页面error.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>出错啦</title>
</head>
<body>
<h1 align="center">${message}</h1>
</body>
</html>

配置web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>springmvc</display-name>
  <!--配置加载spring.xml文件-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:异常处理/spring.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


  <!--配置前端控制器-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--初始化用的-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:异常处理/spring-mvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

三、部署

略;

四、使用

启动项目,访问http://localhost:8080/xxx,界面如下:

springsecurity异常处理机制 springmvc的异常处理机制_xml_03


如果将Controller层修改一下,如下:

springsecurity异常处理机制 springmvc的异常处理机制_spring_04


再次启动,访问:

springsecurity异常处理机制 springmvc的异常处理机制_spring_05