自学内容网 自学内容网

springMVC的异常处理

目录

一、创建项目

二、web.xml

三、spring-mvc.xml

四、异常处理思路

五、springMVC的异常处理

1.controller层

(1)自己处理异常

(2)使用异常处理器

①RoleController类

②自定义异常类SysException类

③自定义异常处理器SysExceptionResolver类

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

⑤jsp页面 error.jsp

⑥运行


一、创建项目

二、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">
    <!--配置解决中文乱码问题的过滤器-->
    <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 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类

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()方法

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)

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类

这个里面的逻辑是写死的

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
<!--配置异常处理器-->
<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/目录下

<%--
  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>
⑥运行

控制台


原文地址:https://blog.csdn.net/2201_76081438/article/details/145133764

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!