关于SpringMVC的异常处理机制详细解读

 更新时间:2023年05月16日 09:56:36   作者:bfhonor  
这篇文章主要介绍了关于SpringMVC的异常处理机制详细解读,SpringMVC是目前主流的Web MVC框架之一,本文将分析SpringMVC的异常处理内容,需要的朋友可以参考下

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";
    }
}

在这里插入图片描述

到此这篇关于关于SpringMVC的异常处理机制详细解读的文章就介绍到这了,更多相关SpringMVC的异常处理机制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Springboot @Configuration与自动配置详解

    Springboot @Configuration与自动配置详解

    这篇文章主要介绍了SpringBoot中的@Configuration自动配置,在进行项目编写前,我们还需要知道一个东西,就是SpringBoot对我们的SpringMVC还做了哪些配置,包括如何扩展,如何定制,只有把这些都搞清楚了,我们在之后使用才会更加得心应手
    2022-07-07
  • Java中volatile关键字的作用是什么举例详解

    Java中volatile关键字的作用是什么举例详解

    这篇文章主要介绍了Java中volatile关键字的作用是什么的相关资料,volatile关键字在Java中用于修饰变量,提供可见性和禁止指令重排的特性,但不保证原子性,它通过内存屏障实现这些特性,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-04-04
  • 工厂方法在Spring框架中的运用

    工厂方法在Spring框架中的运用

    这篇文章介绍了工厂方法在Spring框架中的运用,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-10-10
  • Spring Boot详解五种实现跨域的方式

    Spring Boot详解五种实现跨域的方式

    跨域指的是浏览器不能执⾏其他⽹站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制,这篇文章主要介绍了springboot实现跨域的5种方式,需要的朋友可以参考下
    2022-06-06
  • MybatisPlus 多租户架构(Multi-tenancy)实现详解

    MybatisPlus 多租户架构(Multi-tenancy)实现详解

    这篇文章主要介绍了MybatisPlus 多租户架构(Multi-tenancy)实现详解,详细的介绍了什么是多租户架构以及使用MybatisPlus实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • SpringBoot集成Swagger2生成接口文档的方法示例

    SpringBoot集成Swagger2生成接口文档的方法示例

    我们提供Restful接口的时候,API文档是尤为的重要,它承载着对接口的定义,描述等,本文主要介绍了SpringBoot集成Swagger2生成接口文档的方法示例,需要的朋友们下面随着小编来一起学习学习吧
    2018-12-12
  • java web中使用cookie记住用户的账号和密码

    java web中使用cookie记住用户的账号和密码

    这篇文章主要介绍了java web中使用cookie记住用户的账号和密码的相关资料,需要的朋友可以参考下
    2017-01-01
  • Springboot和bootstrap实现shiro权限控制配置过程

    Springboot和bootstrap实现shiro权限控制配置过程

    这篇文章主要介绍了Springboot和bootstrap实现shiro权限控制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Springboot使用Security实现OAuth2授权验证完整过程

    Springboot使用Security实现OAuth2授权验证完整过程

    安全管理是软件系统必不可少的的功能。根据经典的“墨菲定律”——凡是可能,总会发生。如果系统存在安全隐患,最终必然会出现问题,这篇文章主要介绍了SpringBoot使用Security实现OAuth2授权验证完整过程
    2022-12-12
  • 全网最全Mybatis-Plus详解

    全网最全Mybatis-Plus详解

    Mybatis-Plus是一个Mybatis(opens new window)的增强工具,在Mybatis的基础上只做增强不做改变,为简化开发,这篇文章主要介绍了全网最全Mybatis-Plus详解,需要的朋友可以参考下
    2024-05-05

最新评论