springmvc全局异常处理

文章目录

  • 前言
  • 1、导入依赖
  • 2、配置springmvc.xml文件
  • 3、配置web.xml文件
  • 4、编写异常处理组件
  • 5、编写测试controller
  • 6、准备异常处理页面
  • 7、测试


前言

在基于Servlet-JSP技术开发的项目中,异常的显示是和前后端分离项目不同的。项目业务层所报出的异常会影响浏览器的页面展示,出现404,500,等常见的浏览器提供的报错页面。这样的话十分影响用户体验。springmvc支持自定义全局异常处理,可以自定义异常处理页面,增强用户体验。


1、导入依赖

 <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>5.3.24version>
    dependency>

    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>4.0.1version>
    dependency>

    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>1.18.24version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.13.3version>
    dependency>
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>

2、配置springmvc.xml文件


<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/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"> 

    
    <mvc:annotation-driven/>

    
    <mvc:default-servlet-handler/>

    
    <context:component-scan base-package="com.wmj"/>

    
            <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    
                    <property name="prefix" value="/WEB-INF/jsp">property>
                    
                    <property name="suffix" value=".jsp">property>
            bean>

beans>

3、配置web.xml文件

DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
  servlet>

  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>

4、编写异常处理组件

package com.wmj.handler;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * --效率,是成功的核心关键--
 *
 * @Author lzl
 * @Date 2023/2/16 09:46
 */
@Configuration
public class MyExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {
        System.out.println("执行异常处理类");
        ModelAndView view = new ModelAndView();
        if(ex instanceof NullPointerException){
            view.addObject("msg","空指针异常");
        }else if(ex instanceof ArrayIndexOutOfBoundsException){
            view.addObject("msg","数组下标越界异常");
        }else if(ex instanceof ArithmeticException){
            view.addObject("msg","算数异常");
        }else{
            view.addObject("msg",ex.getMessage());
        }
        view.setViewName("/error");
        return view;
    }
}

5、编写测试controller

package com.wmj.controller;

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


/**
 * --效率,是成功的核心关键--
 *
 * @Author lzl
 * @Date 2023/2/16 09:59
 */
@Controller
@RequestMapping("/exception")
public class ExceptionController {
    @RequestMapping("/test")
    public String testException(){
        int[] arr = new int[3];
        arr[0] = 1;
        arr[1] = 1;
        arr[2] = 1;
        arr[3] = 2;
        //此时下标越界
        return "success";
    }
}

6、准备异常处理页面

默认访问首页跳转测试controller

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!h2>
<a href="http://localhost:8080/exception/test">点一下跳转a>
body>
html>

异常处理页打印信息

<%--
  Created by IntelliJ IDEA.
  User: 我是谁
  Date: 2023/2/16
  Time: 09:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
${msg}
body>
html>

7、测试

springmvc全局异常处理_第1张图片
成功


你可能感兴趣的:(JavaWeb,springmvc,servlet,java,spring)