SpringBoot增强Controller方法@ControllerAdvice注解的使用详解

 更新时间:2023年10月12日 10:31:19   作者:fengyehongWorld  
这篇文章主要介绍了SpringBoot增强Controller方法@ControllerAdvice注解的使用详解,@ControllerAdvice,是Spring3.2提供的新注解,它是一个Controller增强器,可对controller进行增强处理,需要的朋友可以参考下

一. @ControllerAdvice注解作用

@ControllerAdvice ,是Spring3.2提供的新注解,它是一个Controller增强器,可对controller进行增强处理。

  • 配合@ExceptionHandler注解,进行全局异常处理。
  • 配合@InitBinder注解,用来设置WebDataBinder,用于自动绑定前台请求参数到Model中,全局数据预处理,多用于表单提交数据或者url传参。
  • 配合@ModelAttribute注解,让Controller类中所有的方法都可以获取到通过@ModelAttribute注解设置的值,进行全局数据绑定。

注意: @ControllerAdvice 注解将作用在所有Controller层的方法上。

二. @ControllerAdvice注解 + assignableTypes属性

作用:增强指定 .class 的类,非指定的Controller类不会被增强

2.1 @ControllerAdvice增强类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// 指定增强S001LoginController和S002LogoutController
@ControllerAdvice(assignableTypes = {S001LoginController.class, S002LogoutController.class})
public class S_Controller {
    @Autowired
    private HttpServletRequest request;
	// 方式1: @ModelAttribute注解的使用
    @ModelAttribute
    public void initData1(Model model) {
        request.setAttribute("num1", 66);
        model.addAttribute("userMail", List.of("123@mail.com", "456@mail.com"));
    }
	// 方式2: @ModelAttribute注解的使用
    @ModelAttribute(name = "userInfo")
    public Map<String, String> initData2() {
        request.setAttribute("num2", 99);
       return new HashMap<>(){
           {
               put("name", "贾飞天");
               put("age", "18");
           }
       };
    }
	// 捕获S001LoginController或S002LogoutController类中的Exception异常
    @ExceptionHandler(Exception.class)
    public void exceptionHandle(Exception ex) {
        System.out.println(ex.getMessage());
    }
}

2.2 Controller层

目录结构如下

  • s_controller包
    • S001LoginController.java
    • S002LogoutController.java
    • S003Controller.java

说明

  • @ControllerAdvice增强类中,指定对S001LoginController.java和S002LogoutController.java进行了增强,因此这两个类中可以获取到增强类中放入的数据,并且这两个类中抛出的Exception异常也会被增强类所捕获。
  • 由于S003Controller.java并没有被增强,因此该类无法获取增强类中放入的数据,并且抛出的异常也无法被增强类捕获。

S001LoginController.java

有2种方式可以获取出@ControllerAdvice增强类中放入Model中的数据

  1. model.asMap()
  2. @ModelAttribute("key名称") 类型 变量名

还可以通过request.getAttribute("key名称")来获取放入request的attribute中的数据。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/ss001")
public class S001LoginController {
    @Autowired
    private HttpServletRequest request;
    @GetMapping("/init")
    public ModelAndView init(Model model) {
		// ?方式1: 获取出@ControllerAdvice增强类中提前放入Model中的数据
        Map<String, Object> mapInfo = model.asMap();
        Object userMailObj = mapInfo.get("userMail");
        List<String> userMailList = (List<String>)userMailObj;
        System.out.println(userMailList);  // [123@mail.com, 456@mail.com]
        Map<String, String> userInfoMap = (Map<String, String>) mapInfo.get("userInfo");
        System.out.println(userInfoMap);  // {name=贾飞天, age=18}
		// ?获取出@ControllerAdvice增强类中提前放入request的attribute中的数据
        Integer num1 = (Integer) request.getAttribute("num1");
        System.out.println(num1);  // 66
        Integer num2 = (Integer) request.getAttribute("num2");
        System.out.println(num2);  // 99
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("s001");
        return modelAndView;
    }
    @GetMapping("/showInfo")
    @ResponseBody
    public void showInfo(
    		// ?方式2: 获取出@ControllerAdvice增强类中提前放入Model中的数据
            @ModelAttribute("userMail") List<String> userMail
            , @ModelAttribute("userInfo") Map<String, String> userInfo
    ) {
        System.out.println(userMail);  // [123@mail.com, 456@mail.com]
        System.out.println(userInfo);  // {name=贾飞天, age=18}
    }
}

S002LogoutController.java

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
@Controller
@RequestMapping("/ss002")
public class S002LogoutController {
    @GetMapping("/init")
    public ModelAndView init(Model model) {
		// 获取出@ControllerAdvice增强类中提前放入Model中的数据
        Map<String, Object> mapInfo = model.asMap();
        System.out.println(mapInfo);
		// 代码出现异常
        int num = 1 / 0;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("s002");
        return modelAndView;
    }
}

S003Controller.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/ss003")
public class S003Controller {
    @GetMapping("/init")
    public ModelAndView init() {
        int num = 1 / 0;
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("s003");
        return modelAndView;
    }
}

2.3 效果

获取数据

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

异常

在这里插入图片描述

三. @ControllerAdvice注解 + basePackages属性

增强指定包下面所有的Controller

3.1 @ControllerAdvice增强类

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice(basePackages = {"com.example.jmw.t_controller"})
public class T_Controller {
    @ExceptionHandler(Exception.class)
    public void exceptionHandle(Exception ex) {
        System.out.println(ex.getMessage());
    }
}

四. @ControllerAdvice注解 + annotations属性

增强标记了 指定注解 的所有的Controller

4.1 自定义注解

import java.lang.annotation.*;
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerMarkAnnotation {
}

4.2 @ControllerAdvice增强类

mport org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice(annotations = ControllerMarkAnnotation.class)
public class X_Controller {
    @ExceptionHandler(Exception.class)
    public void exceptionHandle(Exception ex) {
        System.out.println(ex.getMessage());
    }
}

到此这篇关于SpringBoot增强Controller方法@ControllerAdvice注解的使用详解的文章就介绍到这了,更多相关SpringBoot的@ControllerAdvice注解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中缀表达式转后缀表达式流程详解

    Java中缀表达式转后缀表达式流程详解

    中缀表达式是一个通用的算术或逻辑公式表示方法。,中缀表达式不容易被计算机解析,但仍被许多程序语言使用,因为它符合人们的普遍用法。本文介绍了实现中缀表达式的方法,需要的可以参考一下
    2022-09-09
  • 基于zipoutputStream的简单使用

    基于zipoutputStream的简单使用

    这篇文章主要介绍了基于zipoutputStream的简单使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • 浅谈spring boot 1.5.4 异常控制

    浅谈spring boot 1.5.4 异常控制

    下面小编就为大家带来一篇浅谈spring boot 1.5.4 异常控制。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06
  • 测量Java对象所占内存大小方式

    测量Java对象所占内存大小方式

    这篇文章主要介绍了测量Java对象所占内存大小方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • 详解Java的Spring框架中bean的注入集合

    详解Java的Spring框架中bean的注入集合

    这篇文章主要介绍了详解Java的Spring框架中bean的注入集合,Spring是Java的SSH三大web开发框架之一,需要的朋友可以参考下
    2015-12-12
  • java IO实现电脑搜索、删除功能的实例

    java IO实现电脑搜索、删除功能的实例

    下面小编就为大家带来一篇java IO实现电脑搜索、删除功能的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-12-12
  • Java中RabbitMQ队列实现RPC详解

    Java中RabbitMQ队列实现RPC详解

    这篇文章主要介绍了Java中RabbitMQ队列实现RPC详解,在本教程中,我们将使用RabbitMQ构建一个RPC系统:一个客户端和一个RPC服务器,我们将创建一个返回斐波那契数字的模拟RPC服务,,需要的朋友可以参考下
    2023-08-08
  • 详解关于Windows10 Java环境变量配置问题的解决办法

    详解关于Windows10 Java环境变量配置问题的解决办法

    这篇文章主要介绍了关于Windows10 Java环境变量配置问题的解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • java微信开发API第二步 获取和回复消息

    java微信开发API第二步 获取和回复消息

    这篇文章主要为大家详细介绍了java微信开发API第二步,获取消息和回复消息,感兴趣的小伙伴们可以参考一下
    2016-06-06
  • Java递归求和1+2+3+...+n实例详解

    Java递归求和1+2+3+...+n实例详解

    在本篇文章里小编给大家带来了关于Java递归求和1+2+3+...+n实例内容,需要的朋友们可以学习参考下。
    2020-01-01

最新评论