springMVC的异常处理

目录

一、创建项目

二、web.xml

三、spring-mvc.xml

四、异常处理思路

五、springMVC的异常处理

1.controller层

(1)自己处理异常

(2)使用异常处理器

①RoleController类

②自定义异常类SysException类

③自定义异常处理器SysExceptionResolver类

④配置异常处理器spring-mvc.xml

[⑤jsp页面 error.jsp](#⑤jsp页面 error.jsp)

⑥运行


一、创建项目

二、web.xml

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">
    <!--配置解决中文乱码问题的过滤器-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--指定使用编码集-->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--前端控制器-->
    <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>*.do</url-pattern>
    </servlet-mapping>
</web-app>

三、spring-mvc.xml

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!-- 配置spring创建容器时要扫描的包 -->
    <context:component-scan base-package="com.qcby.controller"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 配置spring开启注解mvc的支持-->
    <!--    <mvc:annotation-driven></mvc:annotation-driven>-->
</beans>

四、异常处理思路

Controller调用service,service调用dao,异常都是向上抛的,最终有DispatcherServlet找异常处理器进行异常的处理

五、springMVC的异常处理

1.controller层

(1)自己处理异常

RoleController类

java 复制代码
package com.qcby.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/role")
public class RoleController {
    /*
    * 自己处理异常
    * */
    @RequestMapping("/findAll1.do")
    public String findAll1(){
        try {
            System.out.println("执行了。。。");
            //模拟异常
            int i = 1/0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }
}

运行:

控制台:

(2)使用异常处理器

自定义异常,自己处理JDK没有提供的异常,给用户一个友好提示界面提示

①RoleController类

加了一个findAll2()方法

java 复制代码
package com.qcby.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/role")
public class RoleController {
    /*
    * 自己处理异常
    * */
    @RequestMapping("/findAll1.do")
    public String findAll1(){
        try {
            System.out.println("执行了。。。");
            //模拟异常
            int i = 1/0;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }

    /*
    * 使用异常处理器
    * */
    @RequestMapping("/findAll2.do")
    public String findAll2(){
        System.out.println("执行了。。。");
        //模拟异常
        int i = 1/0;
        return "success";
    }
}
②自定义异常类 SysException类

(自己定义的异常都要实现Exception)

java 复制代码
package com.qcby.utils;

/*
* 自定义异常类
* */
public class SysException extends Exception{
    //提示消息
    private String message;

    public SysException(String message) {
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
③自定义异常处理器 SysExceptionResolver类

这个里面的逻辑是写死的

java 复制代码
package com.qcby.utils;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
* 自定义异常处理器
* */
public class SysExceptionResolver implements HandlerExceptionResolver {
    /*
    * 程序出现异常,调用异常处理器中的方法
    * */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //在控制台打印异常信息
        e.printStackTrace();
        //做强转
        SysException exception=null;
        //判断
        if(e instanceof SysException){
            exception=(SysException)e;
        }else {
            exception=new SysException("系统正在维护,请联系管理员");
        }
        //存入异常提示信息
        ModelAndView mv=new ModelAndView();
        mv.addObject("errorMsg",e.getMessage());
        //设置跳转的页面
        mv.setViewName("error");
        return mv;
    }
}
④配置异常处理器spring-mvc.xml
XML 复制代码
<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="com.qcby.utils.SysExceptionResolver"></bean>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!-- 配置spring创建容器时要扫描的包 -->
    <context:component-scan base-package="com.qcby"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--配置异常处理器-->
    <bean id="sysExceptionResolver" class="com.qcby.utils.SysExceptionResolver"></bean>

    <!-- 配置spring开启注解mvc的支持-->
    <!--    <mvc:annotation-driven></mvc:annotation-driven>-->
</beans>
⑤jsp页面 error.jsp

在/WEB-INF/pages/目录下

html 复制代码
<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2024/11/8
  Time: 10:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>错误信息提示页面</title>
</head>
<body>

    <h3>错误的友好提示页面</h3>
    ${errorMsg}    

</body>
</html>
⑥运行

控制台

相关推荐
_waylau20 小时前
“Java+AI全栈工程师”问答01:Spring MVC登录页面错误提示
java·开发语言·vue.js·后端·spring·mvc·springcloud
Cyan_RA921 小时前
SpringMVC 视图和视图解析器 万字详解
java·spring·mvc·springmvc·请求重定向·modelandview·视图解析器
盖丽男3 天前
彻底搞懂:前端MVVM、后端MVC、DDD极致面向对象的区别与落地真相
前端·mvc
Cyan_RA98 天前
SpringMVC 请求数据绑定与参数映射 详解
java·后端·spring·mvc·springmvc·映射请求数据
Cyan_RA910 天前
SpringMVC REST 详解
java·spring·mvc·springmvc·restful·jquery·jsp
budingxiaomoli13 天前
Spring Web MVC 知识总结
spring·mvc
虾米Life14 天前
MVC与MVVM 架构
架构·mvc·mvvm
笛卡尔的心跳16 天前
Spring MVC 注解
java·spring·mvc
小松加哲16 天前
Spring MVC 核心原理全解析
java·spring·mvc
那个失眠的夜17 天前
RESTful 语法规范 核心注解详解
java·spring·mvc·mybatis