【學習總結】在SpringBoot中使用@ControllerAdvice

【學習總結】在SpringBoot中使用@ControllerAdvice

使用@ControllerAdvice實現全局異常處理

1. 建立一個springboot工程
2. 建立異常處理類,在類上添加註解@ControllerAdvice
3. 定義相應的異常處理方法,使用@ExceptionHandler註解標註異常類型
4. 使用異常全局捕獲

代碼如下:
1、建立springboot工程,這裏不再講述,如果不會的可以看這裏
2、建立異常處理類,在類上添加註解@ControllerAdvice
3、定義異常處理方法

import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.NativeWebRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Controller增強器
 *
 * @author jim
 * @date 2017/11/23
 */
/*對ControllerAdvice的學習解釋
可以實現三個功能:全局異常處理、全局數據綁定、全局數據預處理
在類中,可以定義多個方法,不同的方法處理不同的異常
例如專門處理空指針的方法、專門處理數組越界的方法...,
也可以直接在一個方法中處理所有的異常信息。
@ExceptionHandler 註解用來指明異常的處理類型,
即如果指定爲 NullpointerException,則數組越界異常就不會進到這個方法中來。
 */
@ControllerAdvice
public class MyControllerAdvice {
    /**
     * 設置要捕獲的空指針異常,並作出處理
     * 注意:這裏可以試圖返回,也可以放回JSON,這裏就當做一個Controller使用
     *
     * @param request {@link NativeWebRequest}
     * @param e {@link NullPointerException }
     * @return {@link Map}
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Map processUnauthenticatedNullPointerException(NativeWebRequest request, NullPointerException e) {

        System.out.println("===========應用到所有@RequestMapping註解的方法,在其拋出NullPointerException異常時執行");
        Map map = new HashMap(5);
        map.put("code", 404);
        map.put("msg", "空指針異常");
        return map;
    }
    /**
     * 設置要捕獲的異常,並作出處理
     * 注意:這裏可以返回試圖,也可以放回JSON,這裏就當做一個Controller使用
     *
     * @param request {@link NativeWebRequest}
     * @param e {@link Exception}
     * @return {@link Map}
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Map processUnauthenticatedException(NativeWebRequest request, Exception e) {
        System.out.println("===========應用到所有@RequestMapping註解的方法,在其拋出   Exception異常時執行");
        Map map = new HashMap(5);
        map.put("code", 404);
        map.put("msg", e.getMessage());
        return map;
    }
}

4、使用異常處理方法,編寫測試類

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 定義測試類,進行http請求測試
 */
@RestController
public class MyController {
/**
 * 定義方法,測試返回Exception
 */
    @RequestMapping("/show")
    public String show() throws Exception {
        throw new Exception("測試異常");
    }
    /**
 * 定義方法,測試返回無異常
 */
    @RequestMapping("/nomal")
    public String nomal() throws Exception {
        return "正常程序";
    }
    /**
 * 定義方法,測試返回NullPointerException
 */
    @RequestMapping("/showNullPoint")
    public String showNullPoint() throws Exception {
        throw new NullPointerException();
    }
}

5、啓動工程,訪問網站
訪問正常代碼
訪問空指針代碼
訪問異常代碼

使用@ControllerAdvice實現全局數據初始化

全局數據初始化功能可以用來做一些初始化的數據操作,我們可以將一些公共的數據定義在添加了 @ControllerAdvice 註解的類中,這樣,在每一個 Controller 的接口中,就都能夠訪問導致這些數據。
1. 建立一個springboot工程
2. 建立數據初始化類,在類上添加註解@ControllerAdvice
3. 定義相應的初始化數據方法,使用 @ModelAttribute(name =“lxc”)註解標註數據名稱
4. 在Controller中進行數據獲取

代碼如下
1、 建立一個springboot工程
2、建立數據初始化類,在類上添加註解@ControllerAdvice
3、 定義相應的初始化數據方法,使用 @ModelAttribute(name =“lxc”)註解標註數據名稱


import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.HashMap;
import java.util.Map;

/**
 * 定義全局數據,進行全局數據初始化
 */
@ControllerAdvice
public class MyGlobalData {
    /**
     * 使用 @ModelAttribute 註解標記該方法的返回數據是一個全局數據
     * 默認情況下,全局數據的 key 就是返回的變量名,value 就是方法返回值
     * 開發者可以通過 @ModelAttribute 註解的 name 屬性去重新指定 key。
     * @return
     */
    @ModelAttribute(name ="lxc")
    public Map<String,Object> getMyData(){
        Map<String,Object>map=new HashMap<>();
        map.put("name","lili");
        map.put("isBoy","yes");
        return map;
    }
}

4、在Controller中進行數據獲取


import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
/**
 * 定義測試類,進行http請求,測試全局數據初始化
 */
@RestController
public class GetDataController {
    /**
     *獲取全局數據的方法
     * @param model
     * @return
     */
    @GetMapping("/getData")
    public Object getData(Model model){
        Map<String,Object> map=model.asMap();
        System.out.println(map);
        return map.get("lxc");
    }
}

5、啓動工程,訪問網站
在這裏插入圖片描述

使用@ControllerAdvice實現全局數據綁定

1. 建立一個springboot工程
2. 建立實體類
3. 建立數據綁定類,在類上添加註解@ControllerAdvice
4. 定義相應的數據綁定方法方法,使用 @InitBinder(“school”)進行實體綁定
5. 在Controller中進行數據綁定獲取

代碼如下:
1、建立springboot工程,這裏不再講述,如果不會的可以看這裏
2、建立實體類

public class Classes {
    private  String name;
    private int studentNumbers;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getStudentNumbers() {
        return studentNumbers;
    }
}

public class School {
   private String name;
   private int classNumbers;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getClassNumbers() {
        return classNumbers;
    }
    public void setClassNumbers(int classNumbers) {
        this.classNumbers = classNumbers;
    }
}

3、建立數據綁定類,在類上添加註解@ControllerAdvice
4、 定義相應的數據綁定方法方法,使用 @InitBinder(“school”)進行實體綁定

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

@ControllerAdvice
public class MyBindData {
    /**
     * 學校屬性的綁定
     * @param binder
     */
     @InitBinder("school")
    public void initSchool(WebDataBinder binder){
      binder.setFieldDefaultPrefix("school.");
     }

    /**班級屬性的綁定
     * @param binder
     */
    @InitBinder("classes")
    public void initClasses(WebDataBinder binder){
        binder.setFieldDefaultPrefix("classes.");
    }
}

5、定義Controller進行數據綁定測試


import com.example.advice.entity.School;
import com.example.advice.entity.Classes;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestController;

/**
 * 定義測試類,進行http請求,測試全局數據綁定
 */
@RestController
public class GetInitData {
    @GetMapping("/getInputData")
    public String getInputData(School school,Classes classes){
        StringBuilder stringBuilder=new StringBuilder();
        if(school!=null&&classes!=null){
            stringBuilder.append(school.getName());
            stringBuilder.append("學校有");
            stringBuilder.append(school.getClassNumbers());
            stringBuilder.append("個班級,其中");
            stringBuilder.append(classes.getName());
            stringBuilder.append("班是尖子班,有");
            stringBuilder.append(classes.getStudentNumbers());
            stringBuilder.append("個學生");
        }
        return stringBuilder.toString();
    }
    @GetMapping("/getInputDataBind")
    public String getInputDataBind(@ModelAttribute("school") School school,@ModelAttribute("classes") Classes classes){
        StringBuilder stringBuilder=new StringBuilder();
        if(school!=null&&classes!=null){
            stringBuilder.append(school.getName());
            stringBuilder.append("學校有");
            stringBuilder.append(school.getClassNumbers());
            stringBuilder.append("個班級,其中");
            stringBuilder.append(classes.getName());
            stringBuilder.append("班是尖子班,有");
            stringBuilder.append(classes.getStudentNumbers());
            stringBuilder.append("個學生");
        }
        return stringBuilder.toString();
    }
}

6、在網頁中請求測試
未使用綁定的請求:
在這裏插入圖片描述
使用綁定的請求:
在這裏插入圖片描述

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