温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringMvc异常处理器怎么实现

发布时间:2022-03-14 16:04:01 来源:亿速云 阅读:153 作者:iii 栏目:web开发

这篇文章主要讲解了“SpringMvc异常处理器怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringMvc异常处理器怎么实现”吧!

SpringMvc 异常处理器

简介

  SpringMvc 在处理请求过程中出现异常信息由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

异常理解

  异常包含编译时异常和运行时异常,其中编译时异常也叫预期异常。运行时异常只有在项目运行的情况下才会发现,编译的时候不需要关心。

  运行时异常,比如:空指针异常、数组越界异常,对于这样的异常,只能通过程序员丰富的经验来解决和测试人员不断的严格测试来解决。

  编译时异常,比如:数据库异常、文件读取异常、自定义异常等。对于这样的异常,必须使用 try catch代码块或者throws关键字来处理异常。

异常处理思路

  系统中异常包括两类:预期异常(编译时异常)和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试等手段减少运行时异常的发生。

  系统的dao、service、controller出现都通过throws Exception向上抛出,最后由SpringMvc前端控制器交给异常处理器进行异常处理,如下图:

SpringMvc异常处理器怎么实现

 全局范围只有一个异常处理器。

自定义异常类

第一步:CustomException.java

package com.cyb.ssm.exception;

/**
 * 自定义编译时异常
 * 
 * @author apple
 *
 */
public class CustomException extends Exception {
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public CustomException(String msg) {
        super();
        this.msg = msg;
    }
}

第二步:CustomExceptionResolver.java(重点)

package com.cyb.ssm.resolver;

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

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

import com.cyb.ssm.exception.CustomException;

public class CustomExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        String message="";
        // 异常处理逻辑
        if (ex instanceof CustomException) {
            message = ((CustomException) ex).getMsg();
        } else {
            message="未知错误";
        }
        ModelAndView mv=new ModelAndView();
        mv.setViewName("error");
        mv.addObject("message", message);
        return mv;
    }
}

第三步:在springmvc.xml中加入bean

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 处理器类的扫描 -->
    <context:component-scan
        base-package="com.cyb.ssm.controller"></context:component-scan>
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!-- 显示配置视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 配置自定义的转换服务 -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <!-- 自定义日期类型转换器 -->
                <bean class="com.cyb.ssm.controller.converter.DateConverter"></bean>
            </set>
        </property>
    </bean>
    <!-- 配置异常处理器 -->
    <bean class="com.cyb.ssm.resolver.CustomExceptionResolver"></bean>
</beans>

第四步:jsp错误页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
    ${message }
</body>
</html>

第五步:测试类

@RequestMapping("queryItem")
    public ModelAndView queryItem() throws CustomException {
        //查询数据库,用静态数据模拟
        List<Item> itemList = Service.queryItemList();
        ModelAndView mvAndView = new ModelAndView();
        mvAndView.addObject("itemList", itemList);
        //设置视图(逻辑路径)
        mvAndView.setViewName("item/item-list");
        if (true) {
            throw new CustomException("我是自定义异常类");
        }
        return mvAndView;
    }

SpringMvc异常处理器怎么实现

感谢各位的阅读,以上就是“SpringMvc异常处理器怎么实现”的内容了,经过本文的学习后,相信大家对SpringMvc异常处理器怎么实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI