SpringMVC——异常处理

异常处理的思路

在这里插入图片描述
SpringMVC项目中,Controller调用service,service调用dao,若出现异常,异常都是向上抛出的,最终是由DispatcherServletHandlerExceptionResolver进行异常处理。

示例代码

编写jsp代码

<%@page contentType="text/html; charset=UTF-8" language="java"  isELIgnored="false" %>

<html>
    <head>
        <title>requestMapping的使用</title>
    </head>
    <body>
        <h3>实现异常处理器接口 处理异常</h3>
        <a href="testException">测试异常处理</a>
    </body>
</html>

编写异常类

package com.liang.exception;

/**
 * 自定义异常处理类
 */
public class CustomException extends Exception {

    private String message;

    public CustomException(String message) {
        this.message = message;
    }

    public String getMessage()
    {
        return message;
    }
}

自定义异常处理器

package com.liang.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义异常处理器
 */
public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

        e.printStackTrace();
        CustomException customException = null;
        if(e instanceof CustomException){
            customException = (CustomException) e;
        }else{
            customException = new CustomException("系统错误,请与系统管理员联系!!!");
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message",customException.getMessage());
        modelAndView.setViewName("exception");
        return modelAndView;
    }
}

编写异常处理友好页面(exception.jsp)

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>执行失败</title>
</head>
<body>
    执行失败!!!<br/>
    ${message}
</body>
</html>

配置自定义处理器(SpringMVC配置文件)

    <!--配置自定义异常处理器-->
    <bean id="customExceptionResolver" class="com.liang.exception.CustomExceptionResolver"></bean>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值