主頁 > 後端開發 > SpringMVC 決議(三) Controller 注解

SpringMVC 決議(三) Controller 注解

2022-02-17 06:18:58 後端開發

我在前面的文章中介紹了Spring MVC最核心的組件DispatcherServlet,DispatcherServlet把Servlet容器(如Tomcat)中的請求和Spring中的組件聯系到一起,是SpringWeb應用的樞紐,但是我們在日常開發中往往不需要詳細知道樞紐的作用,我們只需要處理樞紐分發給我們的請求,Spring中處理請求業務邏輯最常見的組件是Controller,本文會對Spring的Controller及相關組件做詳細介紹,

Controller的定義

Controller是Spring中的一個特殊組件,這個組件會被Spring識別為可以接受并處理網頁請求的組件,Spring中提供了基于注解的Controller定義方式:@Controller和@RestController注解,基于注解的Controller定義不需要繼承或者實作介面,用戶可以自由的定義介面簽名,以下為Spring Controller定義的示例,

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String handle(Model model) {
        model.addAttribute("message", "Hello World!");
        return "index";
    }
}

@Controller注解繼承了Spring的@Component注解,會把對應的類宣告為Spring對應的Bean,并且可以被Web組件管理,@RestController注解是@Controller和@ResponseBody的組合,@ResponseBody表示函式的回傳不需要渲染為View,應該直接作為Response的內容寫回客戶端,

映射關系RequestMapping

路徑的定義

定義好一個Controller之后,我們需要將不同路徑的請求映射到不同的Controller方法之上,Spring同樣提供了基于注解的映射方式:@RequestMapping,通常情況下,用戶可以在Controller類和方法上面添加@RequestMapping注解,Spring容器會識別注解并將滿足路徑條件的請求分配到對應的方法進行處理,在下面的示例中,"GET /persons/xxx"會呼叫getPerson方法處理,

@RestController
@RequestMapping("/persons")
class PersonController {

    @GetMapping("/{id}")
    public Person getPerson(@PathVariable Long id) {
        // ...
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public void add(@RequestBody Person person) {
        // ...
    }
}

路徑的匹配

Spring支持兩種路徑匹配方式,二者之間可以很好的兼容,Spring默認使用PathPattern進行路徑的匹配,

  1. PathPattern:使用預決議的方法匹配路徑,專門為Web路徑匹配而設計,可以支持復雜的運算式,執行效率很高,
  2. AntPathMatcher:Spring中用于類路徑、檔案系統和其它資源的解決方案,效率比較低,

PathPattern基本可以向下兼容AntPathMatcher的邏輯,并且支持路徑變數和"**"多段路徑匹配,以下列出幾種PathPattern的示例:

路徑示例 說明
/resources/ima?e.png 路徑中有一個字符是可變的,如/resources/image.png
/resources/*.png 路徑中多個字符是可變的,如/resources/test.png
/resources/** 路徑中多段可變,如/resources/test/path/xxx
/projects/{project}/versions 匹配一段路徑,并且把路徑中的值提取出來,如/projects/MyApp/versions
/projects/{project:[a-z]+}/versions 匹配一段符合正則運算式路徑,并且把路徑中的值提取出來,如/projects/myapp/versions

路徑中匹配到的變數可以使用@PathVariable獲取,Path變數可以是方法或者類級別的,匹配到的變數會自動進行型別轉換,如果轉換失敗則會拋出例外,

@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
    // ...
}

@Controller
@RequestMapping("/owners/{ownerId}")
public class OwnerController {

    @GetMapping("/pets/{petId}")
    public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
        // ...
    }
}

路徑沖突

當一次請求匹配到多個Pattern,那么就需要選出最接近的Pattern路徑,Spring為Pattern和AntPathMatcher提供了選擇最接近的路徑策略,二者之間邏輯相近,此處只介紹PathPattern,對于PathPattern,Spring提供了PathPattern.SPECIFICITY_COMPARATOR用于對比路徑之間的優先級,對比的規則如下:

  1. null的pattern具有最低優先級,
  2. 包含通配符的pattern的具有最低優先級(如/**),
  3. 如果兩個pattern都包含通配符,長度比較長的有更高的優先級,
  4. 包含越少匹配符號和越少路徑變數的pattern有越高的優先級,
  5. 路徑越長的優先級越高,

Spring 5.3之后不再支持.*后綴匹配,默認情況下“/person”就會匹配到所有的 “/person.*”

接受和回傳引數的型別

RequestMapping還可以指定介面接受什么型別的引數以及回傳什么型別的引數,這通常會在請求頭的Content-Type中指定:

@PostMapping(path = "/pets", consumes = "application/json") 
public void addPet(@RequestBody Pet pet) {
    // ...
}

@GetMapping(path = "/pets/{petId}", produces = "application/json") 
@ResponseBody
public Pet getPet(@PathVariable String petId) {
    // ...
}

根據引數或Header選擇

RequestMapping還支持按照請求的引數或者Header判斷是否處理請求,

  • 如只接受引數myParam的值為myValue的情況,可以通過如下方式指定:

    @GetMapping(path = "/pets/{petId}", params = "myParam=myValue") 
    public void findPet(@PathVariable String petId) {
        // ...
    }
    
  • 如只接受請求頭中myParam的值為myValue的情況,可以通過如下方式指定:

    @GetMapping(path = "/pets", headers = "myHeader=myValue") 
    public void findPet(@PathVariable String petId) {
        // ...
    }
    

編程式注冊RequestMapping

我們前面的教程中講的都是怎么通過@RequestMapping進行路徑的映射,使用這種方式會自動把路徑映射為添加了注解的方法,這種方式雖然使用很方便,但是靈活性方面有一些欠缺,如果我想要根據Bean的配置資訊動態映射路徑之間的關系時,注解的方式就無法做到這種需求,Spring提供了一種動態注冊RequestMapping的方法,注冊示例如下所示:

@Configuration
public class MyConfig {

    // 從容器中獲取維護映射關系的RequestMappingHandlerMapping和自定義組件UserHandler
    @Autowired
    public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler) 
            throws NoSuchMethodException {

        // 生成路徑匹配資訊
        RequestMappingInfo info = RequestMappingInfo
                .paths("/user/{id}").methods(RequestMethod.GET).build(); 

        // 獲取需要映射的方法
        Method method = UserHandler.class.getMethod("getUser", Long.class); 

        // 注冊路徑和方法之間的映射資訊
        mapping.registerMapping(info, handler, method); 
    }
}

處理方法

通過RequestMapping映射通常可以把依次請求映射到某個方法,這個方法就是處理方法(Handler Methods),處理方法的引數和回傳值可以使用很多請求中的資訊(如@RequestParam, @RequestHeader)等,這些引數支持使用Optional進行封裝,

方法引數 說明
WebRequest, NativeWebRequest 包含了請求引數、請求和Session資訊,主要用于Spring框架內部決議引數等操作
javax.servlet.ServletRequest, javax.servlet.ServletResponse Servlet的請求和引數資訊
javax.servlet.http.HttpSession 請求的Session資訊
javax.servlet.http.PushBuilder 服務器推送是HTTP/2協議中的新特性之一,旨在通過將服務器端的資源推送到瀏覽器的快取中來預測客戶端的資源需求,以便當客戶端發送網頁請求并接收來自服務器的回應時,它需要的資源已經在快取中,這是一項提高網頁加載速度的性能增強的功能,在Servlet 4.0中,服務器推送功能是通過PushBuilder實體公開的,此實體是從HttpServletRequest實體中獲取的,
java.security.Principal 當前用戶的登錄資訊
HttpMethod 請求的方式,如GET,POST等
java.util.Locale 請求中的國際化資訊
java.util.TimeZone + java.time.ZoneId 請求的時區資訊
java.io.InputStream, java.io.Reader 用于獲取請求原始Body的輸入流
java.io.OutputStream, java.io.Writer 用于寫回回應的輸出流
@PathVariable 路徑變數,如"/pets/{petId}"中的petId
@MatrixVariable 用分號分割的引數,如GET /pets/42;q=11;r=22
@RequestParam 獲取請求中的引數,包含multipart型別的檔案
@RequestHeader 請求頭資訊
@CookieValue 請求中的Cookie資訊
@RequestBody 把請求的Body,會使用HttpMessageConverter轉為指定的型別的資料,
HttpEntity<B> 類似于@RequestBody
@RequestPart 用于獲取multipart/form-data中的資料
java.util.Map, org.springframework.ui.Model, org.springframework.ui.ModelMap 獲取用于渲染HTML視圖的引數
@ModelAttribute 用于獲取模型中的屬性
Errors, BindingResult 獲取引數校驗結果資訊
SessionStatus + class-level @SessionAttributes Session資訊
UriComponentsBuilder 獲取匹配程序中的引數資訊
@SessionAttribute 獲取一個Session屬性
@RequestAttribute 獲取請求中的屬性

處理方法也可以支持很多型別的回傳值,不同型別的回傳有不同的意義,

回傳引數 說明
@ResponseBody @RestController就包含了這個注解,這個注解表示使用HttpMessageConverter把回傳值寫入Response,不會進行視圖決議
HttpEntity<B>, ResponseEntity<B> 和@ResponseBody類似,回傳值直接寫入Response
HttpHeaders 只回傳Header不回傳body
String 按斬訓傳值去查找View,并決議為模型
View 回傳一個視圖
java.util.Map, org.springframework.ui.Model 用于渲染視圖的模型,View由RequestToViewNameTranslator決定
@ModelAttribute 用于渲染視圖的模型,View由RequestToViewNameTranslator決定
ModelAndView 回傳一個可用的模型視圖
void 通常表示沒有回傳Body
DeferredResult<V> 異步回傳結果,后文詳細介紹
Callable<V> 異步回傳結果,后文詳細介紹
ListenableFuture<V>, java.util.concurrent.CompletionStage<V>, java.util.concurrent.CompletableFuture<V> 類似于DeferredResult,異步回傳呼叫結果
ResponseBodyEmitter, SseEmitter 異步的把HttpMessageConverter轉換后的Body寫入Response
StreamingResponseBody 把回傳異步寫入Response
Reactive types?—?Reactor, RxJava, or others through ReactiveAdapterRegistry Flux場景下的異步回傳

型別轉換

網路請求的引數往往是String型別的,而映射到后端時需要轉為處理方法需要的資料型別(如@RequestParam, @RequestHeader, @PathVariable, @MatrixVariable 和 @CookieValue),這種情況下Spring會獲取容器內的型別轉換服務和屬性編輯器進行轉換,用戶也可以向WebDataBinder中注入自己需要的轉換服務,

Matrix引數

Matrix引數其實時RFC3986中關于Url編碼的一些規范,Matrix引數之間用分號分割,Matrix引數的多個值之間用逗號分割,例如/cars;color=red,green;year=2012,多個值之間也允許用分號分割,如color=red;color=green;color=blue

如果一個URL需要包含Matrix引數,那么包含Matrix引數應該是一個路徑變數,否則Matrix引數會對路徑匹配造成影響:

// GET /pets/42;q=11;r=22

// 最后一段路徑必須為路徑變數{petId},否則會造成路徑匹配失敗
@GetMapping("/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {

    // petId == 42
    // q == 11
}

不僅僅URL最后一段可以加Matrix引數,URL的任意一段都可以家Matrix引數,如下所示:

// GET /owners/42;q=11/pets/21;q=22

@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
        @MatrixVariable(name="q", pathVar="ownerId") int q1,
        @MatrixVariable(name="q", pathVar="petId") int q2) {

    // q1 == 11
    // q2 == 22
}

Matrix引數允許設定默認值,用戶沒有傳該引數的時候使用這個默認值:

// GET /pets/42

@GetMapping("/pets/{petId}")
public void findPet(@MatrixVariable(required=false, defaultValue="https://www.cnblogs.com/yuhushen/p/1") int q) {

    // q == 1
}

如果路徑中包含很多Matrix引數,一個一個接收可能比較麻煩,我們可以通過MultiValueMap用集合的形式去接收:

// GET /owners/42;q=11;r=12/pets/21;q=22;s=23

@GetMapping("/owners/{ownerId}/pets/{petId}")
public void findPet(
        @MatrixVariable MultiValueMap<String, String> matrixVars,
        @MatrixVariable(pathVar="petId") MultiValueMap<String, String> petMatrixVars) {

    // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
    // petMatrixVars: ["q" : 22, "s" : 23]
}

如果你需要在程式中使用Matrix引數,需要的配置UrlPathHelperremoveSemicolonContent=false

@RequestParam

@RequestParam用于把請求中的引數(查詢引數或者表單引數)系結到對應的方法引數上,默認情況下不允許請求引數中不包含指定的引數,不過用戶可以指定required=false去允許設定請求引數到對應的方法引數,如果方法的引數型別不為String型別,Spring會自動進行型別轉換,當@RequestParam注解的引數型別為Map<String, String>并且@RequestParam沒有指定引數名稱的時候,Spring會把所有的引數注入到Map中,

@Controller
@RequestMapping("/pets")
public class EditPetForm {

    // ...

    @GetMapping
    public String setupForm(@RequestParam("petId") int petId, Model model) { 
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }

    // ...

}

@RequestHeader

一次Http請求往往會包含請求頭和Body兩部分,我們可以通過@RequestHeader把請求頭和處理方法的引數進行系結,@RequestHeader同樣支持Map,假設一次請求有如下的頭:

Host                    localhost:8080
Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language         fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding         gzip,deflate
Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive              300

如果我們需要在方法中獲取Accept-Encoding和Keep-Alive標簽,我們可以通過如下代碼獲取:

@GetMapping("/demo")
public void handle(
        @RequestHeader("Accept-Encoding") String encoding, 
        @RequestHeader("Keep-Alive") long keepAlive) { 
    //...
}

@CookieValue

如果我們需要獲取一次請求中的cookie資訊,我們可以通過@CookieValue獲取,獲取方法如下所示:

@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) { 
    //...
}

@ModelAttribute

@ModelAttribute可以把請求中的引數映射為物件,然后傳遞給對應的方法,

@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute Pet pet) {
    // method logic...
}

上面的例子中,請求引數可以來自pet可以來自以下幾種途徑:

  1. 在請求預處理的程序中添加的@ModelAttribute屬性中的pet;
  2. 從HttpSession中的@SessionAttributes屬性中查找pet;
  3. 從請求引數或者pathVariable中查找pet屬性;
  4. 使用默認的建構式初始化資料,
@PutMapping("/accounts/{account}")
public String save(@ModelAttribute("account") Account account) {
    // ...
}

@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) { 
    if (result.hasErrors()) {
        return "petForm";
    }
    // ...
}
@ModelAttribute
public AccountForm setUpForm() {
    return new AccountForm();
}

@ModelAttribute
public Account findAccount(@PathVariable String accountId) {
    return accountRepository.findOne(accountId);
}

@PostMapping("update")
public String update(@Valid AccountForm form, BindingResult result,
        @ModelAttribute(binding=false) Account account) { 
    // ...
}

@SessionAttributes 和 @SessionAttribute

@SessionAttributes用于在多個請求之間共享Session資料,該注解只能加載類之上,在第一次請求的時候,會把Session資料放入SessionAttributes中,Session結束的時候清除資料,

@Controller
@SessionAttributes("pet") // 把資料放入Session中
public class EditPetForm {

    // 從Session中查詢資料
    @PostMapping("/pets/{id}")
    public String handle(Pet pet, BindingResult errors, SessionStatus status) {
        if (errors.hasErrors) {
            // ...
        }
            // 清空Session中的資料.
            status.setComplete(); 
            // ...
        }
    }
}

如果Session的屬性不由Controller管理,而是其它組件管理(如Filter管理),我們就可以使用@SessionAttribute去把Session中的資料和處理方法中的引數進行系結,

@RequestMapping("/")
public String handle(@SessionAttribute User user) { 
    // ...
}

@RequestAttribute

@RequestAttribute和@SessionAttributes類似,一個是請求級別的,一個是Session級別的,此處不做詳細介紹,

@GetMapping("/")
public String handle(@RequestAttribute Client client) { 
    // ...
}

Multipart引數

我們在前面的文章中說過,DispatcherServlet中會包含MultipartResolver組件,如果一次請求的資料為multipart/form-data型別,DispatcherServlet會把上傳的檔案決議為MultipartFile格式的檔案,Servlet3中也支持使用 javax.servlet.http.Part代替MultipartFile接收檔案,上傳多個檔案的時候可以使用串列或者Map獲取引數,

@Controller
public class FileUploadController {

    @PostMapping("/form")
    public String handleFormUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file) {

        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();
            // store the bytes somewhere
            return "redirect:uploadSuccess";
        }
        return "redirect:uploadFailure";
    }
}

Multipart也可以把需要接收的檔案封裝為物件進行接收,

class MyForm {

    private String name;

    private MultipartFile file;

    // ...
}

@Controller
public class FileUploadController {

    @PostMapping("/form")
    public String handleFormUpload(MyForm form, BindingResult errors) {
        if (!form.getFile().isEmpty()) {
            byte[] bytes = form.getFile().getBytes();
            // store the bytes somewhere
            return "redirect:uploadSuccess";
        }
        return "redirect:uploadFailure";
    }
}

除了通過瀏覽器上傳檔案,我們還可以通過RestFul方式以Json的格式上傳檔案:

POST /someUrl
Content-Type: multipart/mixed

--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="meta-data"
Content-Type: application/json; charset=UTF-8
Content-Transfer-Encoding: 8bit

{
    "name": "value"
}
--edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp
Content-Disposition: form-data; name="file-data"; filename="file.properties"
Content-Type: text/xml
Content-Transfer-Encoding: 8bit
... File Data ...
@PostMapping("/")
public String handle(@RequestPart("meta-data") MetaData metadata,
        @RequestPart("file-data") MultipartFile file) {
    // ...
}

@RequestBody和HttpEntity

@RequestBody應該是日常開發中使用最多的引數之一了,我們可以通過@RequestBody把請求中的Body和處理方法中的引數物件進行系結,Spring會呼叫HttpMessageConverter服務把請求中的資料反序列化為處理方法中的引數物件,@RequestBody還可以和@Validated注解組合進行使用,如果校驗失敗會拋出例外或者交給用戶處理校驗例外資訊,

@PostMapping("/accounts")
public void handle(@Valid @RequestBody Account account, BindingResult result) {
    // ...
}

HttpEntity和@RequestBody的原理類似,不過會把請求體封裝到HttpEntity中,

@PostMapping("/accounts")
public void handle(HttpEntity<Account> entity) {
    // ...
}

@ResponseBody和ResponseEntity

@ResponseBody表示會把回傳值通過HttpMessageConverter直接序列化為String寫入Response,我們平時使用比較多的@RestController就是由@ResponseBody和@Controller組成,

@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle() {
    // ...
}

ResponseEntity和@ResponseBody,不過回傳的基礎上會包含狀態碼和回傳頭等資訊,

@GetMapping("/something")
public ResponseEntity<String> handle() {
    String body = ... ;
    String etag = ... ;
    return ResponseEntity.ok().eTag(etag).build(body);
}

JSON Views

Spring內置了對JacksonJSON的支持,并且支持Jackson的Json序列化視圖,在使用@ResponseBody和ResponseEntity返會資料時,可以按照@JsonView來指定Json序列化時需要顯示的欄位,

@RestController
public class UserController {

    @GetMapping("/user")
    @JsonView(User.WithoutPasswordView.class)
    public User getUser() {
        return new User("eric", "7!jd#h23");
    }
}

public class User {

    public interface WithoutPasswordView {};
    public interface WithPasswordView extends WithoutPasswordView {};

    private String username;
    private String password;

    public User() {
    }

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @JsonView(WithoutPasswordView.class)
    public String getUsername() {
        return this.username;
    }

    @JsonView(WithPasswordView.class)
    public String getPassword() {
        return this.password;
    }
}

我們也可以通過編程的方式實作物件的不同視圖的序列化,使用方法如下所示:

@RestController
public class UserController {

    @GetMapping("/user")
    public MappingJacksonValue getUser() {
        User user = new User("eric", "7!jd#h23");
        MappingJacksonValue value = https://www.cnblogs.com/yuhushen/p/new MappingJacksonValue(user);
        value.setSerializationView(User.WithoutPasswordView.class);
        return value;
    }
}

對于基于View的解決方案,我們可以在Model中添加對應的物件以及Json序列化視圖,使用的示例如下所示:

@Controller
public class UserController extends AbstractController {

    @GetMapping("/user")
    public String getUser(Model model) {
        model.addAttribute("user", new User("eric", "7!jd#h23"));
        model.addAttribute(JsonView.class.getName(), User.WithoutPasswordView.class);
        return "userView";
    }
}

Model物件

Spring中的model物件負責在控制器和展現資料的視圖之間傳遞資料,Spring提供了@ModelAttribute去獲取和寫入Model物件的屬性,@ModelAttribute有多種使用方式:

  1. 在處理方法的入參上添加@ModelAttribute,可以獲取WebDataBinder中已經有的Model中的屬性值,
  2. 在類上(如Controller)添加@ModelAttribute注解,則會為所有的請求初始化模型,
  3. 在處理方法的回傳值上添加@ModelAttribute,表示回傳值會作為模型的屬性,
@ModelAttribute
public void populateModel(@RequestParam String number, Model model) {
    model.addAttribute(accountRepository.findAccount(number));
    // add more ...
}

@ModelAttribute
public Account addAccount(@RequestParam String number) {
    return accountRepository.findAccount(number);
}

DataBinder

前面我們講了很多如何把請求引數和處理方法入參進行系結的注解或者型別,并且知道請求引數需要經過型別轉換才能轉為對應型別的資料,然而注解只是一個標記,并不會實際執行引數系結和型別轉換操作,Spring中必定有一個組件進行引數系結和型別轉換,這個組件就是WebDataBinder,WebDataBinder有一下作用:

  1. 將請求中的引數和處理方法引數進行系結;
  2. 把請求中Spring型別的資料轉為處理方法的引數型別;
  3. 對渲染表單的資料進行格式化,

Spring給用戶提供了修改WebDataBinder的介面,用戶可以在Controller中定義被@InitBinder注解的方法,在方法中修改WebDataBinder的定義:

@Controller
public class FormController {

    @InitBinder 
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    // ...
}

例外處理

在關于DispatcherServlet相關的章節中,我們知道了DispatcherServlet包含了例外決議組件,當例外發生的時候會對例外進行決議,日常開發中使用比較多的例外處理組件是ExceptionHandlerExceptionResolver,用于在遇到例外時,使用帶有@ExceptionHandler注解的方法處理對應的例外,該方法可以定義中Controller或者ControllerAdvice中,

@Controller
public class SimpleController {

    // ...

    @ExceptionHandler
    public ResponseEntity<String> handle(IOException ex) {
        // ...
    }
    
    @ExceptionHandler({FileSystemException.class, RemoteException.class})
    public ResponseEntity<String> handle(Exception ex) {
        // ...
    }
}

如果我們需要定義很多@ExceptionHandler,我們可以選擇在@ControllerAdvice中定義,而不是在每個Controller中定義,

如果一個例外匹配到多個@ExceptionHandler,Spring會嘗試使用距離例外繼承體系最近的@ExceptionHandler去處理這個例外,

Controller Advice

如果我們需要定義全域的@InitBinder或者@ExceptionHandler,那我們就不應該在Controller中定義這些方法, Spring提供了@ControllerAdvice用于添加全域配置:

// Target all Controllers annotated with @RestController
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}

// Target all Controllers within specific packages
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// Target all Controllers assignable to specific classes
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}

我是御狐神,歡迎大家關注我的微信公眾號:wzm2zsd
qrcode_for_gh_83670e17bbd7_344-2021-09-04-10-55-16

本文最先發布至微信公眾號,著作權所有,禁止轉載!

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/424882.html

標籤:Java

上一篇:從服務間的一次呼叫分析整個springcloud的呼叫程序(二)

下一篇:Spring運算式語言

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more