关于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