zoukankan      html  css  js  c++  java
  • springMVC系统异常处理及自定异常处理

    配置系统异常处理器

    1.后台模拟一个异常

    @RequestMapping(value = "/myexception.do", produces = "text/html;charset=utf-8")
        public String myexception() {
            int a=5/0;
            return "/error.jsp";
        }

    2.未配置系统异常时,前台访问报错500,配置系统异常处理器后成功进入错误页面

    <bean
            class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="defaultErrorView" value="error.jsp"></property>
            <property name="exceptionAttribute" value="ex"></property>
        </bean>

    3.前台页面

     错误页面${ex.message}

    效果图:

    配置自定义异常处理器

    1.创建自定义异常类

    public class MyException extends Exception{
    
        public MyException() {
            super();
        }
    
        public MyException(String message) {
            super(message);
        }
    
    }
    public class NameException extends MyException {
    
        public NameException() {
            super();
        }
    
        public NameException(String message) {
            super(message);
        }
    
    }
    public class AgeException extends MyException {
    
        public AgeException() {
            super();
        }
    
        public AgeException(String message) {
            super(message);
        }
    
    }

    2.配置处理器方法

    @RequestMapping(value = "/exception.do", produces = "text/html;charset=utf-8")
        public String exception(String name, Integer age) throws NameException, AgeException {
            if (!name.equals("admin")) {
                throw new NameException("用户名错误");
            }
            if (age > 40) {
                throw new AgeException("年龄太大");
            }
            return "/result.jsp";
        }

    3.配置applicationContext.xml

    <!-- 注册系统异常处理器 -->
        <bean
            class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="defaultErrorView" value="error.jsp"></property>
            <property name="exceptionAttribute" value="ex"/>
            <!-- 自定义异常处理 -->
            <property name="exceptionMappings">
                <props>
                    <prop key="cn.cnsdhzzl.exception.NameException">/customError/userNameError.jsp</prop>
                    <prop key="cn.cnsdhzzl.exception.AgeException">/customError/userAgeeError.jsp</prop>
                </props>
            </property>
        </bean>

    配置完成,再出现异常时就对进入对应的错误页面

  • 相关阅读:
    安装 Panda3D 并使用原有的Python
    Jupyter Notebook PDF输出的中文支持
    lua的文件管理
    elasticsearch-hadoop.jar, 适用于spark3,hadoop3
    shell中递归遍历指定文件夹下的文件
    JDBC的ResultSet游标转spark的DataFrame,数据类型的映射以TeraData数据库为例
    Pandas一些小技巧
    用c++后缀自动机实现最大公共字符串算法,并封装成Python库
    后缀自动机的python实现
    PYTHON调用C接口(基于Ctypes)实现stein算法最大公约数的计算
  • 原文地址:https://www.cnblogs.com/cnsdhzzl/p/6081239.html
Copyright © 2011-2022 走看看