关于SpringMVC的异常处理机制详细解读
作者:bfhonor 发布时间:2023-01-26 17:32:45
SpringMVC异常处理机制
(一)项目前准备
首先参照文章Spring课程工程构建+SpringMVC简介及其快速入门搭建项目搭建好一个项目
itheima_spring_exception
在创建好的项目里面根据上面的文章,依次
①导入SpringMVC相关坐标
②配置SpringMVC核心控制器DispathcerServlet
③创建Controller类和视图页面
④使用注解配置Controller类中业务方法的映射地址
⑤配置SpringMVC核心文件spring-mvc.xml。
项目基本框架
在DemoService里面创建多个方法,用于测试异常的类型。
package com.itheima.service;
import com.itheima.exception.MyException;
import java.io.FileNotFoundException;
public interface DemoService {
void show1();
void show2();
void show3() throws FileNotFoundException;
void show4();
void show5() throws MyException;
}
DemoServiceImpl实现接口DemoService里面的方法。
package com.itheima.service;
import com.itheima.exception.MyException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DemoServiceImpl implements DemoService{
public void show1(){
System.out.println("抛出类型转换异常...");
Object str = "zhangsan";
Integer num = (Integer) str;
}
public void show2(){
System.out.println("抛出除零异常...");
int i = 1/0;
}
public void show3() throws FileNotFoundException {
System.out.println("文件找不到异常...");
FileInputStream in = new FileInputStream("D:/xxx/xxx/xxx.txt");
}
public void show4(){
System.out.println("空指针异常......");
String str = null;
str.length();
}
public void show5() throws MyException {
System.out.println("自定义异常....");
throw new MyException();
}
}
在DemoController类里面进行调用测试方法,用于异常的展示。
package com.itheima.controller;
import com.itheima.exception.MyException;
import com.itheima.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.FileNotFoundException;
@Controller
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping(value="/show")
public String show(@RequestParam(value="name",required=true) String name) throws FileNotFoundException, MyException {
System.out.println("show running......");
demoService.show1();
//demoService.show2();
//demoService.show3();
//demoService.show4();
//demoService.show5();
return "index";
}
}
在MyException自定义一个异常。
package com.itheima.exception;
public class MyException extends Exception{}
在applicationContex.xml配置DemoServiceImpl的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: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
">
<bean id="demoService" class="com.itheima.service.DemoServiceImpl"></bean>
</beans>
在spring-mvc.xml文件里面进行基本的配置,例如mvc注解驱动、视图管理器、静态资源权限开放以及组件扫描。
<?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
">
<!--1、mvc注解驱动-->
<mvc:annotation-driven/>
<!--2、配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--3、静态资源权限开放-->
<mvc:default-servlet-handler/>
<!--4、组件扫描 扫描Controller-->
<context:component-scan base-package="com.itheima.controller"/>
</beans>
在web.xml文件进行基本的配置,例如 * 、SpringMVC的前端控制器以及映射地址。
<?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">
<!--配置 * -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置SpringMVC的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载Spring-mvc.xml文件,在配置控制器的时候告知配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置映射地址-->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
index.jsp文件
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
error.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>通用的错误提示页面</h1>
</body>
</html>
(二)项目异常测试
2.1 异常处理的思路
系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试等手段减少运行时异常的发生。
系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理,如下图:
2.2 异常处理两种方式
①、使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolverr
②、实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器
2.3 简单异常处理器 SimpleMappingExceptionResolver
SpringMVC已经定义好了该类型转换器,在使用时可以根据项目情况进行相应异常与视图的映射配置
(1)默认错误视图
当我们启动服务器时候,对
localhost:8080/show
进行访问,页面会出现异常
当我们在
spring-mvc.xml
文件中进行异常的配置
<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--默认错误视图-->
<property name="defaultErrorView" value="error"/>
</bean>
再次访问
localhost:8080/show
,页面就不再会出现上次的异常页面。而是显示我们设置的error.jsp页面。
(2)根据错误异常类型,进行自定义设定的错误视图跳转
类型转换异常
<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<map>
<entry key="java.lang.ClassCastException" value="error1"></entry>
</map>
</property>
</bean>
自定义类型异常
<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<map>
<entry key="com.itheima.exception.MyException" value="error2"></entry>
</map>
</property>
</bean>
2.4 自定义异常处理步骤
在
src\main\java
里面创建com.itheima.resolver
包,然后创建MyExceptionResolver异常处理器类
①、创建异常处理器类实现HandlerExceptionResolver
package com.itheima.resolver;
import com.itheima.exception.MyException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyExceptionResolver implements HandlerExceptionResolver {
/*参数Exception 异常对象
* 返回值ModelAndView 跳转到视图信息*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView modelAndView = new ModelAndView();
if (e instanceof MyException){
modelAndView.addObject("info","自定义异常");
}else if (e instanceof ClassCastException){
modelAndView.addObject("info","类转换异常");
}
modelAndView.setViewName("error");
return modelAndView;
}
}
②、在spring-mvc.xml
里面配置异常处理器
<bean id="exceptionResolver" class="com.itheima.exception.MyExceptionResolver"/>
③、在error.jsp
中,编写异常页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>通用的错误提示页面</h1>
<h1>${info}</h1>
</body>
</html>
④测试异常跳转
package com.itheima.controller;
import com.itheima.exception.MyException;
import com.itheima.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.FileNotFoundException;
@Controller
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping(value="/show")
public String show() throws FileNotFoundException, MyException {
System.out.println("抛出类型转换异常...");
Object str = "zhangsan";
Integer num = (Integer) str;
return "index";
}
}
来源:https://zmeng.blog.csdn.net/article/details/129781131


猜你喜欢
- 特别是针对循环或timer处理中需要在窗体控件显示数据时,因后台处理过度繁忙而出现没刷新或者假死现象时,可以使用Application.Do
- cookies的创建:在客户端创建一个username的cookies,其值为oneday,有效期为1天.方法1:Response.Cook
- SQL 映射文件只有很少的几个顶级元素(按照应被定义的顺序列出):cache – 对给定命名空间的缓存配置。cache-ref – 对其他命
- 1.应用实例需求: 演示 Spring-Boot 通过表单注册用户,并支持上传图片2.代码实现代码实现-文件上传创建 templates/u
- 1.我做的是一个动态表格,就是在输入框里每输入一次数据并点击“添加”按钮,表格中就会新增一行记录。<table id="st
- java导出Excel通用方法的实例详解Java导出Excel通用方法,只需要一个list 集合。通用方法改进之处踊跃提出package o
- 首先,通过一张最新(2021.11)的编程语言排名图来了解常见的编程语言:从图中可以看出,C++的排名相对于Python、Java、C来说并
- 这篇文章主要介绍了Java中 switch关键原理及用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需
- 本文实例为大家分享了c语言实现可自定义的游戏地图的具体代码,供大家参考,具体内容如下博主相信每个人都有想做游戏的冲动,那么本文将给出一个用c
- FFmpeg是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。ffmpeg命令参数如下:通用选项-L license
- Unity脚本中枚举类型在inspector面板中文显示,供大家参考,具体内容如下效果:工具脚本:ChineseEnumTool.csusi
- 最新需要在项目启动后立即执行某个方法,然后特此记录下找到的四种方式注解@PostConstruct使用注解@PostConstruct是最常
- 一、简介Lock关键字是Monitor的一种替换用法,lock在IL代码中会被翻译成Monitor. lock (obj) &nb
- 文档合并是一种高效文档处理方式。如果能够有一个方法能将多种不同类型的文档合并成一种文档格式,那么在文档存储管理上将为我们提供极大的便利。因此
- 掌握内存操作流输入和输出都是从文件中来的,当然,也可将输出的位置设置在内存上,这就需要ByteArrayInputStream和ByteAr
- 实例如下:public class ConfigOperator { #region 从配置文件获取V
- 双重循环打印顶点在左上的直角三角形:public static void main(String[] args) { // TO
- 本文实例为大家分享了C#实现图形界面的时钟的具体代码,供大家参考,具体内容如下秒针有跳跃两个格子问题,主要是算法耗时没考虑在TimeTick
- 本文实例为大家分享了java实现猜字母游戏的具体代码,供大家参考,具体内容如下案例需求:StepOne:系统随机生成一组随机的字符数组(不重
- 本文实例为大家分享了Android实现时钟特效的具体代码,供大家参考,具体内容如下效果展示:功能介绍:如果您想换一张背景图,可以点击左下角按