Spring MVC的@ControllerAdvice注解

一 视图

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;  charset=UTF-8">
<title>异常处理示例</title>
<script type="text/javascript"  src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
       $(function(){
         $("#search").click(function(){
                   $.post("${pageContext.request.contextPath}/search",null,
                                function(data){
                      // 处理异常
                           if (data.message)
                           {
                                alert("与服务器交互出现异常:" +  data.message);
                           }
                           else
                           {
                                // 获取服务器响应,显示所有订单信息
                                
                           }
                      },"json");
                      });
       })
     </script>
</head>
<body>

<a href="find">@ControllerAdvice异常处理</a>

<hr>
<button id="search">查询订单(返回JSON)</button>
</body>
</html>

二 控制器及其处理类

1 BookController

package org.fkit.controller;


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

@Controller
public class BookController{
    
    @GetMapping("/find")
    public String find() throws Exception{
        int i = 5/0;
        return "success";
    }

}

2 OrderController

package org.fkit.controller;

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

@Controller
public class OrderController {

    @PostMapping("/search")
    public String search() throws Exception{
        try {
            int i = 5/0;
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            throw new OrderException("订单查询失败!");
        }
    }
}

3 OrderException

package org.fkit.controller;
public class OrderException extends RuntimeException {
     public OrderException() {
           super();
           // TODO Auto-generated constructor stub
     }
     public OrderException(String message, Throwable cause,  boolean enableSuppression, boolean writableStackTrace) {
           super(message, cause, enableSuppression,  writableStackTrace);
           // TODO Auto-generated constructor stub
     }
     public OrderException(String message, Throwable cause) {
           super(message, cause);
           // TODO Auto-generated constructor stub
     }
     public OrderException(String message) {
           super(message);
           // TODO Auto-generated constructor stub
     }
     public OrderException(Throwable cause) {
           super(cause);
           // TODO Auto-generated constructor stub
     }
}

4 GlobalExceptionHandler

package org.fkit.controller;


import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {

    // 处理Exception类型异常
    @ExceptionHandler(value = Exception.class)
    public ModelAndView globalErrorHandler(Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("ex", e);
        mav.setViewName("error");
        return mav;
    }
    
    // 处理OrderException自定义异常
    @ExceptionHandler(value = OrderException.class)
    @ResponseBody
    public Object OrderErrorHandler(Exception e) throws Exception {
        // 创建返回对象Map并设置属性,会被@ResponseBody注解转换为JSON返回
        Map<String, Object> map = new HashMap<>();
        map.put("code", 100);
        map.put("message", e.getMessage());
        map.put("data", "请求失败");
        return map;
    }
    
}

三 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
     xmlns:context="http://www.springframework.org/schema/context"
    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可以自动去扫描base-pack下面的包或者子包下面的java文件,
      如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean  -->
    <context:component-scan base-package="org.fkit.controller"/>
    <!-- 默认配置方案 -->
    <mvc:annotation-driven/>
     <!-- 静态资源处理 -->
    <mvc:default-servlet-handler/>
    
    <!-- 视图解析器  p:prefix属性表示前缀  p:suffix 表示后缀  -->
     <bean id="viewResolver"
           class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/content/" p:suffix=".jsp"/>
    
</beans>

四 测试

Spring MVC的@ControllerAdvice注解

Spring MVC的@ControllerAdvice注解

Spring MVC的@ControllerAdvice注解

 

上一篇:SpringBoot-@ControllerAdvice 拦截异常并统一处理


下一篇:Spring中的统一异常处理