springboot中@ControllerAdvice和@RestControllerAdvice注解用法

x33g5p2x  于2021-09-22 转载在 Spring  
字(2.2k)|赞(0)|评价(0)|浏览(509)

1.@ControllerAdvice和@RestControllerAdvice的作用

1.1 用于处理全局异常

1.1.1 出现异常

package com.yl.controlleradvice.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

/** * 测试出现异常后是否跳转到对应的thymeleaf模板 */
@Controller
public class TestController2 {

    @GetMapping("/test")
    public void test() {
        int a = 1 /0;
    }
}

1.1.2 视图模板

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>error message</h1>
<div th:text="${error}"></div>
</body>
</html>

1.1.3 捕获异常并且跳转到视图

package com.yl.controlleradvice.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

//@RestControllerAdvice
@ControllerAdvice
public class TestController {

    @ExceptionHandler(Exception.class)
    public ModelAndView CustomException(Exception e) {
        ModelAndView modelAndView = new ModelAndView("01");
        modelAndView.addObject("error",e.getMessage());
        return modelAndView;
    }
}

1.2 全局数据绑定

1.2.1 定义全局数据

1.2.2 使用全局数据,哪个controller都可以调用

1.3 全局数据预处理

1.3.1 model

package com.yl.controlleradvice.model;

public class Book {
    private String name;
    private double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
package com.yl.controlleradvice.model;

public class Author {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Author{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

1.3.1 预处理

1.3.1 测试,发现如果没加预处理时的前缀,都会报错

1.4.@ControllerAdvice和@RestControllerAdvice的区别

@ControllerAdvice主要用于返回视图
@RestControllerAdvice主要用于直接返回错误信息

相关文章