ControllerAdvice的幾個應用

2021-10-25 10:46:39 字數 3146 閱讀 2303

設定全域性資料

@controlleradvice 是乙個全域性資料處理元件,因此也可以在 @controlleradvice 中配置全域性資料,使用 @modelattribute 注釋進行配置。

@controlleradvice

public class myglobalexceptionhandler

@modelattribute(value = "info")

public mapuserinfo()

}

獲取全域性資料

在任意請求的 controller 中,方法引數中通過 @modelattribute 可以獲取指定的全域性資料,樣例**如下:

@controller

public class advicetestccontroller

}

我們也可以在請求的 controller 方法引數中的 model 獲取所有的全域性資料,下面**的結果同上面的一樣:

public string hello2(model model)

我們知道無論是 get 請求還是 post 請求,controller 這邊都可以定義乙個實體類來接收這些引數。而 @controlleradvice 結合 @initbinder 還能實現請求引數預處理,即將表單中的資料繫結到實體類上時進行一些額外處理。

問題描述

假設我們有如下兩個實體類 user 和 book:

public class user 

public void setname(string name)

public int getage()

public void setage(int age)

}

public class book 

public void setname(string name)

public float getprice()

public void setprice(float price)

}

如果在 contoller 上需要接收兩個實體類的資料,接收方法可以這麼定義:

@controller

public class hellocontroller

}

但由於兩個實體類中都有 name 屬性,那麼引數傳遞時就會發生混淆。

解決辦法

使用 @controlleradvice 結合 @initbinder 即可解決上面的問題,這裡我們建立乙個全域性的引數預處理配置。

第乙個 @initbinder(「user」) 表示該方法是處理 controller 中 @modelattribute(「user」) 對應的引數。

第二個 @initbinder(「book」) 表示該方法是處理 controller 中 @modelattribute(「book」) 對應的引數。

這兩個方法中給相應的 filed 設定乙個字首。

補充說明:在 webdatabinder 物件中,除了可以設定字首,還可以設定允許、禁止的字段、必填字段以及驗證器等等。

@controlleradvice

@order(-50)

public class myglobalexceptionhandler

@initbinder("book")

public void init2(webdatabinder binder)

}

然後 controller 中方法的引數新增 @modelattribute 註解:

@responsebody

public string hello(@modelattribute("user") user user, @modelattribute ("book") book book)

最後瀏覽器請求引數中新增相應的字首,即可成功區分出 name 屬性:

http://localhost:8082/hello?user.name=liming&user.age=12&book.name=book&price=800.2
基本用法

@controlleradvice 最常見的使用場景就是全域性異常處理。這裡我模擬了乙個空指標異常的處理

如果程式出現空指標異常,此時可以通過 @controlleradvice 結合 @exceptionhandler 定義全域性異常捕獲機制,具體**如下:

//這裡列印了異常資訊返回

@controlleradvice

@order(-50)

public class myglobalexceptionhandler

也可以返回乙個modelandview

下面使用乙個返回引數是 modelandview 的樣例。這裡我們使用的頁面模版為 thymeleaf,所以首先要在 pom.xml 中新增相關依賴。

org.springframework.boot

spring-boot-starter-thymeleaf

@controlleradvice

@order(-50)

public class myglobalexceptionhandler

}

然後在 resources/templates 目錄下建立 error.html 檔案

測試**:

@controller

public class hellocontroller

}

測試:

http://localhost:8082/testnull
補充知識點:

@order(-50) 註解可以控制多個@controlleradvice的配置類的優先順序,數值越小,優先順序越大,也就是說我們如果有另外乙個@controlleradvice標註的類,也有乙個處理空指標異常的方法,以小的那個為標準

參考文章:

SQL server自動備份應注意的幾個問題

這段時間要將公司所有的資料庫統一備份到一台電腦,就想到了用sql server的資料庫維護計畫對資料庫進行異機備份,操作過程中遇到了很多問題,後來一一化解。過程就不詳述了,現將sql server 所有版本 資料庫維護計畫執行資料庫遠端備份的幾個注意點總結如下 1 備份至本地驅動器,如果目標資料夾是...

c 開發應避免的幾個小濫用

一 string和stringbuilder 少量的字串操作不宜採用stringbuilder。由於string是不可變得物件,對於string的疊加,每次操作都會生成乙個新的string物件。所以針對大量string的操作時,我們會採用stringbuilde。但似乎很多人都知道這一點,所以只要字...

變頻調速技術應注意的幾個問題

變頻調速技術現已被應用於各行各業,也應用於水泥廠中並取得了顯著的經濟效益。但從整體上看,在水泥行業的推廣較慢,一些企業採用變頻調速技術以後,也未獲得應有的節能效果。分析其中的原因,是沒有意識到技術創新的重要作用,對變頻調速技術的重要作用了解不夠 有些企業在應用中技術上還沒有過關。以下,筆者就推廣應用...