spring系统学习--spirngMVC之异常处理

   本篇内容记录一下springMVC的异常处理内容。  环境是:springmvc环境搭建

过程如下: 

       1,将错误处理的bean类注册到上下文中。  该bean需要实现一个接口:

   可见,它是spring-webmvc提供的一个接口。  也是web的  : 异常处理的 源头!

    在spring-mvc.xml加入: (实际上,只要能够完成上下文注入这个要求,写在哪里都无所谓,注解也好,配置也好)。

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!-- 定义默认的异常处理页面 -->
        <property name="defaultErrorView" value="defaulterror"/>
        <!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception -->
        <property name="exceptionAttribute" value="ex"/>
        <!-- 定义需要特殊处理的异常,这是重要点 -->
        <property name="exceptionMappings">
            <props>
                <prop key="com.automannn.springMVC_practice.exception.MyException">myerror</prop>
            </props>
            <!-- 还可以定义其他的自定义异常 -->
        </property>
    </bean>

  这是spring-webmvc提供的默认实现。  它为我们预留了一些简单配置的地方: 属性exceptionMappings即可完成要求。 在本次实验中我自定义了一个异常:(需要注意的是,这个视图配置的路径也是基于视图解析路径的。 也就是要使用视图解析器配置的前缀和后缀)

package com.automannn.springMVC_practice.exception;

/**
 * @author [email protected]
 * @time 2018/11/8 11:20
 */
public class MyException extends Exception {

    public MyException(String msg){
        super(msg);
    }
}

2.配置相关视图页面

     本次实验,我随便配置了几个。

<%--
  Created by IntelliJ IDEA.
  User: 14394
  Date: 2018/11/8
  Time: 11:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>defaulterror</title>
</head>
<body>
 This is deafault error!
</body>
</html>
<%--
  Created by IntelliJ IDEA.
  User: 14394
  Date: 2018/11/8
  Time: 11:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>error</title>
</head>
<body>
  This is my error page!
</body>
</html>

    它们位于:

3.新建能抛出该异常的源控制器,以测试自定义的异常处理

   

package com.automannn.springMVC_practice.controller;

import com.automannn.springMVC_practice.exception.MyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;

/**
 * @author [email protected]
 * @time 2018/11/8 11:21
 */
@Controller
public class ExceptionController {
    @GetMapping("/testException")
    public void testException() throws MyException {
        throw new MyException("测试");
    }

    @GetMapping("/testGlobalException")
    public void testGlobalException() throws Exception {
        throw new Exception("测试");
    }
}

4.测试

   运行服务器:

  然而:我们会发现这样一个页面:

   因为状态的这个部分是服务器容器的功能。 而spring-webmvc是基于服务器容器的。 

猜你喜欢

转载自blog.csdn.net/qq_36285943/article/details/83892088