SpringMVC @ControllerAdvice 注解

本文介绍Spring框架中的异常处理机制,特别是通过@ControllerAdvice注解实现全局异常处理的方式。展示了如何定义异常处理器并返回特定视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

@ControllerAdvice注解如果当前Handler中找不到@ExceptionHandler方法来解决当前方法出现的异常,则将去@ControllerAdvice注解标记的类中查找@ExceptionHandler标记的方法来处理异常。

例如(当id = 0时,将出现异常)

index.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
  Created by IntelliJ IDEA.
  User: 23369
  Date: 3/31/2019
  Time: 3:03 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>$Title$</title>
</head>
<body>
<a href="testExceptionHandlerExceptionResolver?id=10">TestExceptionHandlerExceptionResolver</a>
</body>
</html>

error.jsp

<%--
  Created by IntelliJ IDEA.
  User: 23369
  Date: 4/4/2019
  Time: 7:50 PM
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
errorPage

<br>

错误信息是:${requestScope.exception}
</body>
</html>

TestException.class

package com.hello2;

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

@Controller
public class TestException {

/*

若不使用@ControllerAdvice注解,可以直接使用该方式在页面中输出异常信息

 @ExceptionHandler({ArithmeticException.class})
    public String handlerArithmeticException(Exception exception){

        System.out.println("异常" + exception);

        return "error";
    }

*/

   
    @RequestMapping("testExceptionHandlerExceptionResolver")
    public String testExceptionHandlerExceptionResolver(@RequestParam("id") Integer id ){

        System.out.println(10/id);

        return "success";
    }
}

使用 @ControllerAdvice注解

package com.hello2;


import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class HandlerException {

    @ExceptionHandler({ArithmeticException.class})
    public ModelAndView handlerArithmeticException(Exception exception){

        ModelAndView modelAndView = new ModelAndView("error");
        modelAndView.addObject("exception",exception);
        return modelAndView;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值