SpringMVC 异常处理

1. 异常处理两种方式

  • 使用SpringMVC提供的简单异常处理器SimpleMappingExceptionResolver
  • 实现Spring的异常处理接口HandlerExceptionResolver

2. 使用简单异常处理器

2.1 添加依赖

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

2.2 创建jsp文件

  • 在webapp下创建jsp文件夹, 将jsp文件都放入jsp文件夹.
error.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>通用异常处理页面</h1>
</body>
</html>
error01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>类型转换异常</h1>
</body>
</html>
error02.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>算数异常</h1>
</body>
</html>
error03.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>自定义异常</h1>
</body>
</html>
error04.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>文件找不到异常</h1>
</body>
</html>

2.3 编写SpringMVC核心配置文件

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

    <!-- 组件扫描 -->
    <context:component-scan base-package="site.zhouyun" />

    <!-- 开启注解驱动 -->
    <mvc:annotation-driven />

    <!-- 视图解析器 -->
    <bean 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"></property>

        <property name="exceptionMappings">
            <map>
                <!-- key对应异常类型, value对应jsp界面 -->
                <entry key="java.lang.ClassCastException" value="error01"></entry>
                <entry key="java.lang.ArithmeticException" value="error02"></entry>
                <entry key="site.zhouyun.exception.CustomException" value="error03"></entry>
                <entry key="java.io.FileNotFoundException" value="error04"></entry>
            </map>
        </property>
    </bean>
</beans>

2.4 修改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">
    
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <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>

2.5 编写自定义异常

/**
 * 自定义异常, 仅做测试用
 */
public class CustomException extends Exception
{
}

2.6 编写Service

@Service("userService")
public class UserService
{

    public void method01()
    {
        throw new ClassCastException();
    }

    public void method02()
    {
        int i = 1/0;
    }

    public void method03() throws CustomException
    {
        throw new CustomException();
    }

    public void method04() throws FileNotFoundException
    {
        InputStream inputStream = new FileInputStream(new File(""));
    }

    public void method05()
    {
        throw new RuntimeException("手动抛出 RuntimeException 异常");
    }
}

2.7 编写Controller

@Controller
@RequestMapping("user")
public class UserController
{
    @Autowired
    @Qualifier("userService")
    private UserService userService;


    @ResponseBody
    @RequestMapping("method01")
    public void method01()
    {
        userService.method01();
    }

    @ResponseBody
    @RequestMapping("method02")
    public void method02()
    {
        userService.method02();
    }

    @ResponseBody
    @RequestMapping("method03")
    public void method03() throws CustomException
    {
        userService.method03();
    }
    @ResponseBody
    @RequestMapping("method04")
    public void method04() throws FileNotFoundException
    {
        userService.method04();
    }

    @ResponseBody
    @RequestMapping("method05")
    public void method05() throws FileNotFoundException
    {
        userService.method05();
    }
}

2.9 测试

  • 启动项目然后访问http://localhost:8080/user/method(01~05)查看效果.

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3. 自定义异常处理

3.1 修改error.jsp界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>通用异常处理页面</h1>
    <h3>${message}</h3>
</body>
</html>

3.2 编写自定义异常处理类

/**
 * 异常处理类
 */
public class CustomExceptionResolver implements HandlerExceptionResolver
{
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    {
        ModelAndView modelAndView = new ModelAndView();
        if(ex instanceof ClassCastException)
        {
            modelAndView.addObject("message"," 类型转换异常");
        }
        else if(ex instanceof ArithmeticException)
        {
            modelAndView.addObject("message", "算数异常");
        }
        else if(ex instanceof CustomException)
        {
            modelAndView.addObject("message","自定义异常");
        }
        else if(ex instanceof FileNotFoundException)
        {
            modelAndView.addObject("message","文件找不到异常");
        }
        else {
            modelAndView.addObject("message","未知异常, 异常信息: " + ex.getMessage());
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

3.3 修改SringMVC核心配置文件

  • 删除之前配置的异常处理, 然后添加自定义异常处理.
<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 组件扫描 -->
    <context:component-scan base-package="site.zhouyun" />

    <!-- 开启注解驱动 -->
    <mvc:annotation-driven />

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置自定义异常 -->
   <bean class="site.zhouyun.exception.CustomExceptionResolver"></bean>
</beans>

3.4 测试

  • 启动项目然后访问http://localhost:8080/user/method(01~05)查看效果.

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值