SpringBoot增強Controller方法@ControllerAdvice注解的使用詳解
一. @ControllerAdvice注解作用
@ControllerAdvice ,是Spring3.2提供的新注解,它是一個Controller增強器,可對controller進行增強處理。
- 配合@ExceptionHandler注解,進行全局異常處理。
- 配合@InitBinder注解,用來設(shè)置WebDataBinder,用于自動綁定前臺請求參數(shù)到Model中,全局?jǐn)?shù)據(jù)預(yù)處理,多用于表單提交數(shù)據(jù)或者url傳參。
- 配合@ModelAttribute注解,讓Controller類中所有的方法都可以獲取到通過@ModelAttribute注解設(shè)置的值,進行全局?jǐn)?shù)據(jù)綁定。
注意: @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層
目錄結(jié)構(gòu)如下
- s_controller包
- S001LoginController.java
- S002LogoutController.java
- S003Controller.java
說明
- @ControllerAdvice增強類中,指定對S001LoginController.java和S002LogoutController.java進行了增強,因此這兩個類中可以獲取到增強類中放入的數(shù)據(jù),并且這兩個類中拋出的Exception異常也會被增強類所捕獲。
- 由于S003Controller.java并沒有被增強,因此該類無法獲取增強類中放入的數(shù)據(jù),并且拋出的異常也無法被增強類捕獲。
S001LoginController.java
有2種方式可以獲取出@ControllerAdvice增強類中放入Model中的數(shù)據(jù)
- model.asMap()
- @ModelAttribute("key名稱") 類型 變量名
還可以通過request.getAttribute("key名稱")來獲取放入request的attribute中的數(shù)據(jù)。
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中的數(shù)據(jù)
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中的數(shù)據(jù)
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中的數(shù)據(jù)
@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中的數(shù)據(jù)
Map<String, Object> mapInfo = model.asMap();
System.out.println(mapInfo);
// 代碼出現(xiàn)異常
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 效果
獲取數(shù)據(jù)



異常

三. @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屬性
增強標(biāo)記了 指定注解 的所有的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());
}
}到此這篇關(guān)于SpringBoot增強Controller方法@ControllerAdvice注解的使用詳解的文章就介紹到這了,更多相關(guān)SpringBoot的@ControllerAdvice注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis-Plus批量添加或修改數(shù)據(jù)的3種方式總結(jié)
使用Mybatis-plus可以很方便的實現(xiàn)批量新增和批量修改,不僅比自己寫foreach遍歷方便很多,而且性能也更加優(yōu)秀,下面這篇文章主要給大家介紹了關(guān)于Mybatis-Plus批量添加或修改數(shù)據(jù)的3種方式,需要的朋友可以參考下2023-05-05
java驗證用戶是否已經(jīng)登錄 java實現(xiàn)自動登錄
這篇文章主要介紹了java驗證用戶是否已經(jīng)登錄,java實現(xiàn)自動登錄,感興趣的小伙伴們可以參考一下2016-04-04
java實現(xiàn)周期性執(zhí)行(定時任務(wù))
這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)周期性執(zhí)行定時任務(wù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-09-09
Java分支循環(huán)與數(shù)組核心知識點總結(jié)
這篇文章主要介紹了Java分支循環(huán)與數(shù)組核心知識點總結(jié)的相關(guān)資料,理解循環(huán)與分支結(jié)構(gòu)是掌握編程的基礎(chǔ),重復(fù)執(zhí)行操作的循環(huán)和基于條件的執(zhí)行路徑分支有助于構(gòu)建復(fù)雜的程序邏輯,需要的朋友可以參考下2026-01-01
Java對接MQTT協(xié)議的完整實現(xiàn)示例代碼
MQTT是一個基于客戶端-服務(wù)器的消息發(fā)布/訂閱傳輸協(xié)議,MQTT協(xié)議是輕量、簡單、開放和易于實現(xiàn)的,這些特點使它適用范圍非常廣泛,這篇文章主要介紹了Java對接MQTT協(xié)議的完整實現(xiàn),需要的朋友可以參考下2025-08-08
基于idea操作hbase數(shù)據(jù)庫并映射到hive表
這篇文章主要介紹了用idea操作hbase數(shù)據(jù)庫,并映射到hive,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03
Spring結(jié)合WebSocket實現(xiàn)實時通信的教程詳解
WebSocket?是基于TCP/IP協(xié)議,獨立于HTTP協(xié)議的通信協(xié)議,本文將使用Spring結(jié)合WebSocket實現(xiàn)實時通信功能,有需要的小伙伴可以參考一下2024-01-01
SpringBoot Import及自定義裝配實現(xiàn)方法解析
這篇文章主要介紹了SpringBoot Import及自定義裝配實現(xiàn)方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08

