SpringMvc异常处理机制

news2024/10/8 15:46:55

预期异常和运行异常,前者通过捕获,后者通过规范代码开发、测试等手段减少发生概率。 

系统dao层、service层、controller层出现都可通过throws Exception向上抛出,最终由SpringMvc前端控制器交由异常处理器进行异常处理。

 SpringMvc项目异常处理两种方式

1、使用SpringMvc提供的简单异常处理器SimpleMappingExceptionResolver简单映射异常处理器。这种是当产生响应的异常后会跳转到响应的页面,需在spring-mvc.xml中配置。

2、实现Spring的异常处理接口HandlerExceptionResolver,自定义自己的异常处理器。

简单异常处理器SimpleMappingExceptionResolver

创建mavenWeb项目,pom文件引入springMvc依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.5.RELEASE</version>
        </dependency>
    </dependencies>

web.xml配置前端控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--配置SpringMVC的前端控制器:
    配置一个servlet,类选择第三方org.springframework的DispatcherServlet
    配置该类,且路径为拦截所有来作为springMvc的前端控制器servlet  -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param><!--该servlet的初始化参数-->
            <!--spring-mvc.xml是怎么加载的呢
            spring-mvc.xml是怎么加载的呢
            类似web.xml中的<context-param>application域的全局初始化参数。
            这里下面配置初始化参数spring-mvc.xml名称即为web.xml中该DispatcherServlet的servlet的init初始化参数来提供,
            以便org的DispatcherServlet根据这个servlet的init初始化参数去加载springMVC的配置文件,
            继而IOC出controller(特有行为)实例提供给前端控制器DispatcherServlet(共有行为)使用。
            -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup><!--loadOnStartup=负整数或不加默认第一次访问该servlet执行时创建servlet对象并初始化
        loadOnStartup为0或正整数时,web服务器启动时创建servlet对象,数字越小,优先级越高-->
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern><!-- 配置该servlet的路径为拦截所有/,虽会覆盖tomcat静态资源访问路径,但现在没有静态资源html之类,只有jsp动态页面。-->
    </servlet-mapping>
</web-app>

com.kdy.exception中MyException

public class MyException extends Exception{
}

 com.kdy.service.impl中DemoServiceImpl

@Service
public class DemoServiceImpl implements DemoService {
    @Override
    public void show1() {
        System.out.println("抛出异常转换类型...");
        Object str = "zhangsan";
        Integer num =(Integer) str;
    }

    @Override
    public void show2() {
        System.out.println("抛出除零异常");
        int i = 1/0;
    }

    @Override
    public void show3() throws FileNotFoundException {
        System.out.println("文件找不到异常...");
        InputStream in = new FileInputStream("C:/xxx/xxx/xx.txt");
    }

    @Override
    public void show4() {
        System.out.println("空指针异常");
        String str = null;
        str.length();
    }

    @Override
    public void show5() throws MyException {
        System.out.println("自定义异常");
            throw new MyException();
    }
}

com.kdy.controller中DemoController

@Controller
public class DemoController {
    @Autowired
    private DemoService demoService;
    @RequestMapping("/show1")
    public String show1(){
        System.out.println("show running1...");
        demoService.show1();
        return "index";
    }
    @RequestMapping("/show2")
    public String show2(){
        System.out.println("show running2...");
        demoService.show2();
        return "index";
    }
    @RequestMapping("/show3")
    public String show3() throws FileNotFoundException {
        System.out.println("show running3...");
        demoService.show3();
        return "index";
    }
    @RequestMapping("/show4")
    public String show4(){
        System.out.println("show running4...");
        demoService.show4();
        return "index";
    }
    @RequestMapping("/show5")
    public String show5() throws MyException {
        System.out.println("show running5...");
        demoService.show5();
        return "index";
    }
}

resource下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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    ">

    <!--Controller的组件扫描-->
    <context:component-scan base-package="com.kdy"></context:component-scan>
    
    <!--配置内部资源视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property><!--前缀-->
        <property name="suffix" value=".jsp"></property><!--后缀-->
    </bean>
    
    <!--配置异常处理器-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!--<property name="defaultErrorView" value="error"/>--><!--默认异常视图:所有的Exception都走这个,这里由于上面写了视图解析器的前后缀,会把error拼接为/jsp/error.jsp-->
        <property name="exceptionMappings">
            <map>
                <entry key="java.lang.ClassCastException" value="error1"/>
                <entry key="java.lang." value="error1"/>
                <entry key="java.lang.ClassCastException" value="error1"/><!--类转换异常-->
                <entry key="java.lang.ArithmeticException" value="error2"/><!--除零异常-->
                <entry key="java.io.import java.io.FileNotFoundException;" value="error3"/><!--文件找不到异常-->
                <entry key="java.lang.NullPointerException" value="error4"/><!--空指针异常-->
                <entry key="com.kdy.exception.MyException" value="error5"/><!--自定义异常-->
            </map>
        </property>
    </bean>
</beans>

webapp下jsp的创建index.jsp

<h1>index.jsp~~~hello</h1>

webapp下jsp的创建error.jsp

<h1>通用的错误提示页面~</h1>

webapp下jsp的创建error1.jsp

<h1>类型转换异常~</h1>

 webapp下jsp的创建error2.jsp

<h1>除零算数异常~</h1>

webapp下jsp的创建error3.jsp

<h1>文件找不到异常~</h1>

webapp下jsp的创建error4.jsp

<h1>空指针异常异常~</h1>

webapp下jsp的创建error5.jsp

<h1>自定义异常~</h1>

分别访问即可:http://localhost:8080/SpringException/show1... ...

自定义异常处理器,实现HandlerExceptionResolver接口

上面案例,pom文件加上servlet依赖

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

com.kdy.resolver中创建MyExceptionResolver实现HandlerExceptionResolver接口

public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if (e instanceof ClassCastException){
            modelAndView.addObject("info","类转换异常");
        }else if(e instanceof ArithmeticException){
            modelAndView.addObject("info","除零算数异常");
        }else if(e instanceof FileNotFoundException){
            modelAndView.addObject("info","文件找不到异常");
        }else if(e instanceof NullPointerException){
            modelAndView.addObject("info","空指针异常");
        }else if(e instanceof MyException){
            modelAndView.addObject("info","自定义异常");
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

resource下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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    ">
    <!--Controller的组件扫描-->
    <context:component-scan base-package="com.kdy"></context:component-scan>

    <!--配置内部资源视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property><!--前缀-->
        <property name="suffix" value=".jsp"></property><!--后缀-->
    </bean>

    <!--配置异常处理器-->
<!--    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        &lt;!&ndash;<property name="defaultErrorView" value="error"/>&ndash;&gt;&lt;!&ndash;默认异常视图:所有的Exception都走这个,这里由于上面写了视图解析器的前后缀,会把error拼接为/jsp/error.jsp&ndash;&gt;
        <property name="exceptionMappings">
            <map>
                <entry key="java.lang.ClassCastException" value="error1"/>
                <entry key="java.lang." value="error1"/>
                <entry key="java.lang.ClassCastException" value="error1"/>&lt;!&ndash;类转换异常&ndash;&gt;
                <entry key="java.lang.ArithmeticException" value="error2"/>&lt;!&ndash;除零异常&ndash;&gt;
                <entry key="java.io.import java.io.FileNotFoundException;" value="error3"/>&lt;!&ndash;文件找不到异常&ndash;&gt;
                <entry key="java.lang.NullPointerException" value="error4"/>&lt;!&ndash;空指针异常&ndash;&gt;
                <entry key="com.kdy.exception.MyException" value="error5"/>&lt;!&ndash;自定义异常&ndash;&gt;
            </map>
        </property>
    </bean>-->

    <!--自定义异常处理器-->
    <bean class="com.kdy.resolver.MyExceptionResolver"/>
</beans>

webapp的jsp中error.jsp改为

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>error</title>
</head>
<body>
error通用页面~~~~~~
异常类型为${info}
</body>
</html>

启动tomcat部署,访问http://localhost:8080/SpringDemoModule/show1... ...

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/773257.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

有必要买apple pencil吗?ipad触控笔推荐平价

科技的飞速发展改变了人们的生活。在各种电子、数码产品不断涌现的今天&#xff0c;这款能与平板电脑相匹配的电容笔就应运而生了。随着国内的电容笔技术的进步&#xff0c;它的使用领域也在不断地扩展&#xff0c;逐渐开始取代苹果原装电容笔。下面&#xff0c;我将为大家介绍…

IDEA使用GIT提交代码中文日志(commit message)乱码

最近换了新的开发环境&#xff0c;导致提交gti中文注释乱码&#xff0c;遂记录一下解决方案 idea中查看git提交信息显示中文是正常的 gitee上显示乱码 本地显示也是乱码 一、命令修改编码格式 git 安装目录下执行 git config --global i18n.commitencoding utf-8git config …

《爆肝整理》保姆级系列教程-玩转Charles抓包神器教程(6)-Charles安卓手机抓包大揭秘

1.简介 Charles和Fiddler一样不但能截获各种浏览器发出的 HTTP 请求&#xff0c;也可以截获各种智能手机发出的HTTP/ HTTPS 请求。 Charles也能截获 Android 和 Windows Phone 等设备发出的 HTTP/HTTPS 请求。 今天宏哥讲解和分享Charles如何截获安卓移动端发出的 HTTP/HTTP…

2023 年 7 月中旬使用各种随身 wifi 的电脑无法上网的解决方法

微软近日推送了安全更新&#xff0c;在 Win10 下编号为 KB5028166&#xff0c;在 Win11 下编号为 KB5028185。此补丁会导致部分电脑无法上网&#xff0c;主要是使用了各种品牌的随身 Wifi 的电脑。 具体症状表现为从控制面板的网络连接&#xff08;ncpa.cpl&#xff09;打开详细…

vue项目展示pdf文件

记录贴 最近我有个需求,就是在h5页面上展示pdf文件,分页,最后一页有个蒙层阴影渐变的效果,尝试过一些插件,但都不是很好用,最后用了pdfjs-dist加上canvas 可以看下效果 先下载: npm i pdfjs-dist2.5.207下面展示代码 html: <template><canvas v-for"pageNumb…

浅谈设计模式之单例模式

0 单例模式简介 单例模式属于创建型模式&#xff0c;它提供了一种创建对象的最佳方式。单例模式指的是单一的一个类&#xff0c;该类负责创建自己的对象&#xff0c;并且保证该对象唯一。该类提供了一种访问其唯一对象的方法&#xff0c;外部需要调用该类的对象可以通过方法获…

Python 自学 day06 JSON 数据传输,折线图,柱状图,动态柱状图

1.python JSON的知识 1.1 什么是 JSON 答&#xff1a; JSON是一种轻量级的数据交互格式。可以按照JSON指定的格式去组织和封装数据. JSON本质上是一个带有特定格式的字符串。 1.2 JSON 的主要功能 答&#xff1a;json就是一种在各个编程语言中流通的…

栈和队列OJ

文章目录 1.用队列实现栈2.用栈实现队列3.设计循环队列4.循环队列经典题 1.用队列实现栈 typedef int QDataType; typedef struct QueueNode {struct QueueNode* next;QDataType data; }QNode;typedef struct Queue {QNode* head;QNode* tail; }Queue; typedef struct MyStack …

⛳ Java数组

Java数组的目录 ⛳ Java数组&#x1f3a8; 一&#xff0c;一维数组&#x1f463; 1.1&#xff0c;概念&#x1f4e2; 1.2&#xff0c;基本用法1&#xff0c;语法格式2&#xff0c;代码 &#x1f4bb; 1.3&#xff0c;内存结构&#x1f4dd; 1.4&#xff0c;练习 &#x1f381; …

天翎MyApps低代码平台唯品会金牌客服管理系统

项目痛点&#xff1a; 作为一家知名的创新大型电商&#xff0c;唯品会秉承“传承品质生活&#xff0c;提升幸福体验”的企业使命。基于客服铁军锻造项目&#xff0c;实现基于金牌案例的提交、评审、积分&#xff0c;学习功能。 项目中的晋升机制、案例产生学习机制、双激励机制…

赛桨PaddleScience v1.0正式版发布,飞桨科学计算能力全面升级!

AI for Science日益表现出突破传统科学研究能力瓶颈的巨大潜力&#xff0c;正在成为全球科学研究新范式。近年来&#xff0c;各学科不断加入&#xff0c;模型精度、泛化性逐渐提高&#xff0c;不同技术路径、不同应用场景的AI for Science成功应用不断涌现&#xff0c;深度融合…

详解 Spring - Ioc(控制权反转) 和 DI(依赖注入)

目录 Spring 是什么? Ioc Ioc 的优点 DI Ioc 和 DI 的区别 Spring 是什么? 通常情况下 Spring 是指 Spring Framework (Spring 框架), 是一个开源框架, 有着庞大的社区, 这就是他能长久不衰的原因, Spring 支持广泛的应用场景, 他可以让企业级的应用开发起来更简单 S…

Selenium之css如何实现元素定位,你了解多少?

前言 世界上最远的距离大概就是明明看到一个页面元素站在那里&#xff0c;但是我却定位不到&#xff01;&#xff01; Selenium定位元素的方法有很多种&#xff0c;像是通过id、name、class_name、tag_name、link_text等等&#xff0c;但是这些方法局限性太大&#xff0c; 随…

简单认识框架

hi,大家好,好久不见今天为大家带来框架相关的知识 文章目录 &#x1f338;1.框架&#x1f95d;1.1为什么要学习框架 &#x1f338;2.框架的优点&#x1f95d;2.1采用servlet创建项目&#x1f440;2.1.1缺陷 &#x1f95d;2.2采用SpringBoot创建项目&#x1f440;2.2.1优势 &…

Vue-Cli脚手架的安装和使用

文章目录 一、Vue-Cli脚手架的环境准备1. 安装Node.js1-1 去 [Node.js官网](https://nodejs.org/zh-cn/) 下载安装包&#xff0c;修改安装路径到其它盘&#xff0c;如 G:\Program Files1-2 安装npm淘宝镜像&#xff0c;提速 2. 设置 cnpm的下载路径和缓存路径2-1 在安装目录 G:…

Zoho Projects:Jira的理想替代品,让项目管理更高效

在软件开发生命周期中&#xff0c;项目管理一直是一个非常重要的环节。为了更好地协作、追踪项目的进程和管理任务&#xff0c;许多公司选择了Jira这款著名的项目管理工具&#xff0c;它是个非常强大的工具&#xff0c;但同时也有非常明显的缺点。今天&#xff0c;我们将向大家…

知识普及:[18F]FB RGD,18F标记RGD多肽,tumor显像剂,

资料编辑|陕西新研博美生物科技有限公司小编MISSwu​ 为大家介绍&#xff08;CAS&#xff1a;N/A&#xff09;,试剂仅用于科学研究&#xff0c;不可用于人类&#xff0c;非药用&#xff0c;非食用 分子式&#xff1a;C34H44FN9O9 分子量&#xff1a;740.8 中文名称&#xff1a…

linux之Ubuntu系列 系统信息 (一)查看文件、磁盘 、进程

时间和日期 查看当前的系统时间 date 查看日历 -y 显示本年度日历&#xff0c; 不加-y 选项&#xff0c;显示本月日历 cal [-y] 查看磁盘 和 目录 空间 df [-h] df&#xff1a;disk free 显示磁盘可用空间&#xff0c;-h&#xff0c;跟 ls -lh 效果类似&#xff0c;以人性化方…

Python 字典 get()函数使用详解,字典获取值

「作者主页」&#xff1a;士别三日wyx 「作者简介」&#xff1a;CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者 「推荐专栏」&#xff1a;小白零基础《Python入门到精通》 get函数使用详解 1、设置默认返回值2、嵌套字典取值3、get() 和 dict[key] 的区别…