SpringBoot增強(qiáng)Controller方法@ControllerAdvice注解的使用詳解
一. @ControllerAdvice注解作用
@ControllerAdvice ,是Spring3.2提供的新注解,它是一個(gè)Controller增強(qiáng)器,可對(duì)controller進(jìn)行增強(qiáng)處理。
- 配合@ExceptionHandler注解,進(jìn)行全局異常處理。
- 配合@InitBinder注解,用來(lái)設(shè)置WebDataBinder,用于自動(dòng)綁定前臺(tái)請(qǐng)求參數(shù)到Model中,全局?jǐn)?shù)據(jù)預(yù)處理,多用于表單提交數(shù)據(jù)或者url傳參。
- 配合@ModelAttribute注解,讓Controller類(lèi)中所有的方法都可以獲取到通過(guò)@ModelAttribute注解設(shè)置的值,進(jìn)行全局?jǐn)?shù)據(jù)綁定。
注意: @ControllerAdvice 注解將作用在所有Controller層的方法上。
二. @ControllerAdvice注解 + assignableTypes屬性
作用:增強(qiáng)指定 .class 的類(lèi),非指定的Controller類(lèi)不會(huì)被增強(qiáng)
2.1 @ControllerAdvice增強(qiáng)類(lèi)
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;
// 指定增強(qiáng)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類(lèi)中的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
說(shuō)明
- @ControllerAdvice增強(qiáng)類(lèi)中,指定對(duì)S001LoginController.java和S002LogoutController.java進(jìn)行了增強(qiáng),因此這兩個(gè)類(lèi)中可以獲取到增強(qiáng)類(lèi)中放入的數(shù)據(jù),并且這兩個(gè)類(lèi)中拋出的Exception異常也會(huì)被增強(qiáng)類(lèi)所捕獲。
- 由于S003Controller.java并沒(méi)有被增強(qiáng),因此該類(lèi)無(wú)法獲取增強(qiáng)類(lèi)中放入的數(shù)據(jù),并且拋出的異常也無(wú)法被增強(qiáng)類(lèi)捕獲。
S001LoginController.java
有2種方式可以獲取出@ControllerAdvice增強(qiáng)類(lèi)中放入Model中的數(shù)據(jù)
- model.asMap()
- @ModelAttribute("key名稱(chēng)") 類(lèi)型 變量名
還可以通過(guò)request.getAttribute("key名稱(chēng)")來(lái)獲取放入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增強(qiáng)類(lèi)中提前放入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增強(qiáng)類(lèi)中提前放入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增強(qiáng)類(lèi)中提前放入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增強(qiáng)類(lèi)中提前放入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屬性
增強(qiáng)指定包下面所有的Controller
3.1 @ControllerAdvice增強(qiáng)類(lèi)
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屬性
增強(qiáng)標(biāo)記了 指定注解 的所有的Controller
4.1 自定義注解
import java.lang.annotation.*;
@Documented
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerMarkAnnotation {
}4.2 @ControllerAdvice增強(qiáng)類(lèi)
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增強(qiáng)Controller方法@ControllerAdvice注解的使用詳解的文章就介紹到這了,更多相關(guān)SpringBoot的@ControllerAdvice注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mybatis-Plus批量添加或修改數(shù)據(jù)的3種方式總結(jié)
使用Mybatis-plus可以很方便的實(shí)現(xiàn)批量新增和批量修改,不僅比自己寫(xiě)foreach遍歷方便很多,而且性能也更加優(yōu)秀,下面這篇文章主要給大家介紹了關(guān)于Mybatis-Plus批量添加或修改數(shù)據(jù)的3種方式,需要的朋友可以參考下2023-05-05
Java線(xiàn)程池復(fù)用線(xiàn)程的秘密你知道嗎
這篇文章主要為大家詳細(xì)介紹了Java線(xiàn)程池復(fù)用線(xiàn)程的秘密,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望您能夠多多關(guān)注2022-03-03
java驗(yàn)證用戶(hù)是否已經(jīng)登錄 java實(shí)現(xiàn)自動(dòng)登錄
這篇文章主要介紹了java驗(yàn)證用戶(hù)是否已經(jīng)登錄,java實(shí)現(xiàn)自動(dòng)登錄,感興趣的小伙伴們可以參考一下2016-04-04
java實(shí)現(xiàn)周期性執(zhí)行(定時(shí)任務(wù))
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)周期性執(zhí)行定時(shí)任務(wù),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09
Java分支循環(huán)與數(shù)組核心知識(shí)點(diǎn)總結(jié)
這篇文章主要介紹了Java分支循環(huán)與數(shù)組核心知識(shí)點(diǎn)總結(jié)的相關(guān)資料,理解循環(huán)與分支結(jié)構(gòu)是掌握編程的基礎(chǔ),重復(fù)執(zhí)行操作的循環(huán)和基于條件的執(zhí)行路徑分支有助于構(gòu)建復(fù)雜的程序邏輯,需要的朋友可以參考下2026-01-01
Java對(duì)接MQTT協(xié)議的完整實(shí)現(xiàn)示例代碼
MQTT是一個(gè)基于客戶(hù)端-服務(wù)器的消息發(fā)布/訂閱傳輸協(xié)議,MQTT協(xié)議是輕量、簡(jiǎn)單、開(kāi)放和易于實(shí)現(xiàn)的,這些特點(diǎn)使它適用范圍非常廣泛,這篇文章主要介紹了Java對(duì)接MQTT協(xié)議的完整實(shí)現(xiàn),需要的朋友可以參考下2025-08-08
Mybatis分頁(yè)查詢(xún)主從表的實(shí)現(xiàn)示例
本文主要介紹了Mybatis分頁(yè)查詢(xún)主從表的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-09-09
基于idea操作hbase數(shù)據(jù)庫(kù)并映射到hive表
這篇文章主要介紹了用idea操作hbase數(shù)據(jù)庫(kù),并映射到hive,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03
Spring結(jié)合WebSocket實(shí)現(xiàn)實(shí)時(shí)通信的教程詳解
WebSocket?是基于TCP/IP協(xié)議,獨(dú)立于HTTP協(xié)議的通信協(xié)議,本文將使用Spring結(jié)合WebSocket實(shí)現(xiàn)實(shí)時(shí)通信功能,有需要的小伙伴可以參考一下2024-01-01
SpringBoot Import及自定義裝配實(shí)現(xiàn)方法解析
這篇文章主要介紹了SpringBoot Import及自定義裝配實(shí)現(xiàn)方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

