【学习总结】在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、在网页中请求测试
未使用绑定的请求:
在这里插入图片描述
使用绑定的请求:
在这里插入图片描述

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