SpringMVC - @ControllerAdvice三種使用場景

@ControllerAdvice就是@Controller的增強版。@ControllerAdvice主要用來處理全局數據, 一般搭配@ExceptionHandler、@ModelAttribute以及@InitBinder 使用。

一、全局異常處理

@ControllerAdvice可以配合@ ExceptionHandler對所有@Controller標註的方法進行異常捕獲和處理。

@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 捕獲MaxUploadSizeExceededException
     * 文件上傳超過最大限制
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView uploadException(MaxUploadSizeExceededException e){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("maxUpload");
        mv.addObject("message","上傳文件大小超出限制!");
        return mv;
    }
}

返回值可以是JSON、ModelAndView、邏輯視圖等。一般來說,都是返回一個ModelAndView,根據需求制定。

二、添加全局數據

配合@ModelAttribute可以添加一個全局的key-value數據,即是添加到@Controller標記的方法裏的參數Model裏的。

1、創建POJO類

@Data
public class Student {
    /** ID */
    private Long id;
    /** 姓名 */
    private String name;
    /** 性別 */
    private String sex;
    /** 班級 */
    protected String classGrade;
    /** 入學日期 */
    private Date admissionDate;
}

2、配置全局數據

@ControllerAdvice
public class GlobalConfig {

    @ModelAttribute(value = "studentInfo")
    public Student studentInfo(){
        Student student = new Student();
        student.setName("柳成蔭");
        student.setSex("男");
        return student;
    }

3、Controller層調用

@RestController
public class StudentController {
    @GetMapping("/student")
    public Student student(Model model){
        Map<String, Object> map = model.asMap();
        Student student = (Student) map.get("studentInfo");
        return student;
    }

4、測試結果

JSON

三、請求參數預處理

配合@InitBinder能實現請求參數預處理,即將表單中的數據綁定到實體類上時進行一些額外處理
比如說,在一個form表單裏,存在兩個對象,這兩個對象有相同的屬性名,如果不進行預處理,可能會造成數據錯亂。

1、form表單處理

給不同對象的屬性添加前綴

<form action="/bookAndMusic" method="get">
    <input type="text" name="book.name" placeholder="書名"><br>
    <input type="text" name="book.author" placeholder="書作者"><br>
    <input type="text" name="music.name" placeholder="音樂名"><br>
    <input type="text" name="music.author" placeholder="音樂作者"><br>
    <input type="submit" value="提交">
</form>

2、@InitBinder處理參數

@InitBinder裏的值,就是處理Controller層,方法參數裏對應註解@ModelAttribute裏的參數的。

@ControllerAdvice
public class GlobalConfig {
    @InitBinder("book")
    public void initBook(WebDataBinder binder){
        // 設置字段的前綴
        binder.setFieldDefaultPrefix("book.");
    }

    @InitBinder("music")
    public void initMusic(WebDataBinder binder){
        binder.setFieldDefaultPrefix("music.");
    }

3、Controller層處理

@RestController
public class StudentController {

    @GetMapping("/bookAndMusic")
    public String bookAndMusic(@ModelAttribute("book")Book book, @ModelAttribute("music")Music music){
        return book.toString() + "----------" + music.toString();
    }

4、測試結果

表單填寫
結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章