欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringMVC基于配置的异常处理器

时间:2022-06-19 10:25:58|栏目:JAVA代码|点击:

一、基于配置的异常处理

SpringMVC 提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver。

HandlerExceptionResolver接口的实现类有:

DefaultHandlerExceptionResolver,这个是默认使用的处理器,之前遇到的一些异常,其实springMVC 都已经给我们处理过了。

SimpleMappingExceptionResolver,这个可以让我们自定义异常处理。当出现指定的异常,可以设置返回新的视图。

使用SimpleMappingExceptionResolver,在springMVC的配置文件中:

<!--配置异常处理-->
  <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
          <props>
              <prop key="java.lang.ArithmeticException">error</prop>
          </props>
      </property>
  </bean>

示例里使用的一个处理运算异常的类ArithmeticException,里面的值 error 表示异常后跳转的视图。

对应的,新建一个error.html页:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>error</title>
</head>
<body>
出现错误
</body>
</html>

接下来,造一个异常:

@RequestMapping("/testExceptionHandler")
  public String testExceptionHandler() {
      System.out.println(1/0);
      return "success";
  }

正常情况下这个处理器会跳转到 success 页,但是里面有个 1/0的异常,所以会按照配置跳转到 error 页。

重新部署,测试一下,访问http://localhost:8080/springmvc/testExceptionHandler:

成功跳转到 error 页。

储存异常信息

此外,还可以继续属性exceptionAttribute,设置一个key用来存放异常信息,默认存在当前的请求域中:

<!--配置异常处理-->
  <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionMappings">
          <props>
              <prop key="java.lang.ArithmeticException">error</prop>
          </props>
      </property>
      <!--exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享-->
      <property name="exceptionAttribute" value="ex"></property>
  </bean>

那么在 error 页中就可以使用到ex来获取异常信息了。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>error</title>
</head>
<body>
出现错误
<p th:text="${ex}"></p>
</body>
</html>

重新部署,刷新下页面:

二、基于注解的异常处理

springmvc 同样也提供了一套注解,通过注解方式也可以实现上述的异常处理。

新建一个控制器 ExceptionController:

//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
    //@ExceptionHandler 用于设置所标识方法处理的异常
    @ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
    public String testException(Exception ex, Model model){
        // ex表示当前请求处理中出现的异常对象,放到请求域中
        model.addAttribute("ex", ex);
        return "error";
    }
}

@ControllerAdvice将当前类标识为异常处理的组件。

ex表示当前请求处理中出现的异常对象,用Model放到请求域中。

现在注释掉配置文件里的处理器,重新部署下,刷新http://localhost:8080/springmvc/testExceptionHandler:

依然可以。

上一篇:Java常用测试工具大全

栏    目:JAVA代码

下一篇:SpringBoot请求参数相关注解说明小结

本文标题:SpringMVC基于配置的异常处理器

本文地址:http://www.codeinn.net/misctech/205263.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有