search
HomeJavajavaTutorialspringMVC support for exception handling
springMVC support for exception handlingJun 26, 2017 am 09:21 AM
springspringmvcdeal withabnormalsupport

No matter what project you are doing, exception handling is very necessary, and you cannot throw some error codes that only programmers can understand to users, so at this time, perform unified exception handling to show a comparison Friendly error pages are necessary. Like other MVC frameworks, springMVC also has its own exception handling mechanism.
There are two main ways to handle exceptions provided by springMVC. One is to directly implement your own HandlerExceptionResolver. Of course, this also includes using the SimpleMappingExceptionResolver and DefaultHandlerExceptionResolver that Spring has provided us. The other is to use annotations to implement a specialized Controller for handling exceptions - ExceptionHandler.

1. Implement your own HandlerExceptionResolver. HandlerExceptionResolver is an interface. springMVC itself already has its own implementation-DefaultHandlerExceptionResolver. This resolver is just for Some of the more typical exceptions are intercepted and then the corresponding error codes are returned. Of course, you can also inherit the DefaultHandlerExceptionResolver class and then rewrite some of the exception handling methods to implement your own exception handling.

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.springframework.web.servlet.HandlerExceptionResolver;  
import org.springframework.web.servlet.ModelAndView;  
  
public class ExceptionHandler implements HandlerExceptionResolver {  
  
    @Override  public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex) {  // TODO Auto-generated method stub  return new ModelAndView("exception");  
    }  
  
}

The fourth of the above resolveException The parameter indicates which type of exception is handled. Because the Exception class is the base class of all exception classes, if you want to perform different processing according to different exception types, you can perform different processing according to different exception types in the resolveException method and return different exception views. For example:

public class ExceptionHandler implements HandlerExceptionResolver {  
  
    @Override  public ModelAndView resolveException(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex) {  // TODO Auto-generated method stub  if (ex instanceof NumberFormatException) {  //doSomething...  return new ModelAndView("number");  
        } else if (ex instanceof NullPointerException) {  //doSomething...  return new ModelAndView("null");  
        }  return new ModelAndView("exception");  
    }  
  
}

After defining such an exception handler, you must define such a bean object in the applicationContext, such as:

bean id="exceptionResolver" class="com.tiantian.xxx.web.handler.ExceptionHandler"/> ;
##In addition to implementing a DefaultHandlerExceptionResolver, Spring also implements a SimpleMappingExceptionResolver, which Both inherit from the abstract class AbstractHandlerExceptionResolver, and AbstractHandlerExceptionResolver implements the resolveException method of the HandlerExceptionResolver interface, and thus extracts two abstract methods, one is the method prepareResponse (exception, response) that is executed before exception handling, and the other is It is the doResolveException(request, response, handler, exception) method for exception resolution. SimpleMappingExceptionResolver, as its name implies, uses a simple mapping relationship to determine which view should handle the current error message. SimpleMappingExceptionResolver provides the mapping relationship between exceptions and views through exception type exceptionMappings, and provides statusCodes to map the view name returned by the exception and the corresponding HttpServletResponse return code when an exception occurs. And the default value can be specified through defaultErrorView and defaultErrorCode. defaultErrorView means that when the corresponding exception type is not found in exceptionMappings, the view defined by defaultErrorView will be returned. defaultErrorCode means that when an exception occurs, it will not be found in statusCodes, the mapping relationship between the view and the return code. The corresponding mapping is the return code returned by default. When using SimpleMappingExceptionResolver, when an exception occurs, SimpleMappingExceptionResolver will put the current exception object into its own attribute exceptionAttribute. When exceptionAttribute is not specified, exceptionAttribute uses the default value exception.

The following is a simple example:

(1) Declare a SimpleMappingExceptionResolver bean in the SpringMVC servlet configuration file, and configure the attribute exceptionMappings and defaultExceptionView to specify the corresponding relationship between exceptions and views

Xml代码
<bean>  
    <property>  
        <props>  
            <prop>number</prop><!-- 表示当抛出NumberFormatException的时候就返回名叫number的视图 -->  
            <prop>null</prop>  
        </props>  
    </property>  
    <property></property><!-- 表示当抛出异常但没有在exceptionMappings里面找到对应的异常时 返回名叫exception的视图-->  
    <property><!-- 定义在发生异常时视图跟返回码的对应关系 -->  
        <props>  
            <prop>500</prop><!-- 表示在发生NumberFormatException时返回视图number,然后这里定义发生异常时视图number对应的HttpServletResponse的返回码是500 -->  
            <prop>503</prop>  
        </props>  
    </property>  
    <property></property><!-- 表示在发生异常时默认的HttpServletResponse的返回码是多少,默认是200 -->  
</bean>
(2 )Access as follows:

@Controller  
@RequestMapping("/test")  
public class TestController {  
  
    @RequestMapping("/null")  public void testNullPointerException() {  
        Blog blog = null;  //这里就会发生空指针异常,然后就会返回定义在SpringMVC配置文件中的null视图          System.out.println(blog.getId());  
    }  
      
    @RequestMapping("/number")  public void testNumberFormatException() {  //这里就会发生NumberFormatException,然后就会返回定义在SpringMVC配置文件中的number视图  Integer.parseInt("abc");  
    }  
      
    @RequestMapping("/default")  public void testDefaultException() {  if (1==1)  //由于该异常类型在SpringMVC的配置文件中没有指定,所以就会返回默认的exception视图  throw new RuntimeException("Error!");  
    }  
      
}

(3) The exception object that can be accessed in the Jsp page, here is the return view number.jsp of NumberFormatException as an example:

Jsp code
springMVC support for exception handling
  
  
  
nbsp;HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  
    
    <base>">  
      
    <title>My JSP 'number.jsp' starting page</title>  
      
    <meta>  
    <meta>  
    <meta>      
    <meta>  
    <meta>  
    <!--  
    <link rel="stylesheet" type="text/css" href="styles.css?1.1.11">  
    -->  
  
    
    
    
    NumberFormatException. <br>  
    <br>  
    <br><span><!-- 这是JSP中的内置对象exception --></span>  
  
  
  
    <br><span><!-- 这是SpringMVC放在返回的Model中的异常对象 --></span>  
  
  
  
    <span><!-- HttpServletResponse返回的错误码信息,因为前面已经配置了NumberFormatException的错误码返回值为888,所以这里应该显示888 --></span>  
  
  
  
    

(4)当请求/test/number.do的时候会返回定义好的number视图,返回结果如下:


 

2、使用@ExceptionHandler进行处理

 

使用@ExceptionHandler进行处理有一个不好的地方是进行异常处理的方法必须与出错的方法在同一个Controller里面

 

如:

Java代码  springMVC support for exception handling
 
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.ExceptionHandler;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
import com.tiantian.blog.web.servlet.MyException;  
  
@Controller  
public class GlobalController {  
  
      /** 
     * 用于处理异常的 
     * @return 
     */  
    @ExceptionHandler({MyException.class})  public String exception(MyException e) {  
        System.out.println(e.getMessage());  
        e.printStackTrace();  return "exception";  
    }  
      
    @RequestMapping("test")  public void test() {  throw new MyException("出错了!");  
    }  
      
      
}

 

这里在页面上访问test方法的时候就会报错,而拥有该test方法的Controller又拥有一个处理该异常的方法,这个时候处理异常的方法就会被调用

 

 

优先级

既然在SpringMVC中有两种处理异常的方式,那么就存在一个优先级的问题:

 

当发生异常的时候,SpringMVC会如下处理:

(1)SpringMVC会先从配置文件找异常解析器HandlerExceptionResolver

(2)如果找到了异常异常解析器,那么接下来就会判断该异常解析器能否处理当前发生的异常

(3)如果可以处理的话,那么就进行处理,然后给前台返回对应的异常视图

(4)如果没有找到对应的异常解析器或者是找到的异常解析器不能处理当前的异常的时候,就看当前的Controller中有没有提供对应的异常处理器,如果提供了就由Controller自己进行处理并返回对应的视图

(5)如果配置文件里面没有定义对应的异常解析器,而当前Controller中也没有定义的话,那么该异常就会被抛出来。

The above is the detailed content of springMVC support for exception handling. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java Spring怎么实现定时任务Java Spring怎么实现定时任务May 24, 2023 pm 01:28 PM

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

SpringBoot与SpringMVC的比较及差别分析SpringBoot与SpringMVC的比较及差别分析Dec 29, 2023 am 11:02 AM

SpringBoot和SpringMVC都是Java开发中常用的框架,但它们之间有一些明显的差异。本文将探究这两个框架的特点和用途,并对它们的差异进行比较。首先,我们来了解一下SpringBoot。SpringBoot是由Pivotal团队开发的,它旨在简化基于Spring框架的应用程序的创建和部署。它提供了一种快速、轻量级的方式来构建独立的、可执行

Java axios与spring前后端分离传参规范是什么Java axios与spring前后端分离传参规范是什么May 03, 2023 pm 09:55 PM

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

Spring Boot与Spring Cloud的区别与联系Spring Boot与Spring Cloud的区别与联系Jun 22, 2023 pm 06:25 PM

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

Java Spring框架创建项目与Bean的存储与读取实例分析Java Spring框架创建项目与Bean的存储与读取实例分析May 12, 2023 am 08:40 AM

1.Spring项目的创建1.1创建Maven项目第一步,创建Maven项目,Spring也是基于Maven的。1.2添加spring依赖第二步,在Maven项目中添加Spring的支持(spring-context,spring-beans)在pom.xml文件添加依赖项。org.springframeworkspring-context5.2.3.RELEASEorg.springframeworkspring-beans5.2.3.RELEASE刷新等待加载完成。1.3创建启动类第三步,创

比较SpringBoot与SpringMVC的差异是什么?比较SpringBoot与SpringMVC的差异是什么?Dec 29, 2023 am 10:46 AM

SpringBoot与SpringMVC的不同之处在哪里?SpringBoot和SpringMVC是两个非常流行的Java开发框架,用于构建Web应用程序。尽管它们经常分别被使用,但它们之间的不同之处也是很明显的。首先,SpringBoot可以被看作是一个Spring框架的扩展或者增强版。它旨在简化Spring应用程序的初始化和配置过程,以帮助开发人

从零开始学Spring Cloud从零开始学Spring CloudJun 22, 2023 am 08:11 AM

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

Java Spring Bean生命周期管理的示例分析Java Spring Bean生命周期管理的示例分析Apr 18, 2023 am 09:13 AM

SpringBean的生命周期管理一、SpringBean的生命周期通过以下方式来指定Bean的初始化和销毁方法,当Bean为单例时,Bean归Spring容器管理,Spring容器关闭,就会调用Bean的销毁方法当Bean为多例时,Bean不归Spring容器管理,Spring容器关闭,不会调用Bean的销毁方法二、通过@Bean的参数(initMethod,destroyMethod)指定Bean的初始化和销毁方法1、项目结构2、PersonpublicclassPerson{publicP

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft