Loading

SpringBoot @ControllerAdvice 三种使用场景

SpringBoot @ControllerAdvice的三种使用场景

1.概述

@ControllerAdvice 有三个方面的功能:

  • 全局异常处理
  • 全局数据绑定
  • 全局数据预处理

2.全局异常处理

(一)返回字符串

MyGlobalException.java

package com.zhuantai.fileupload.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.multipart.MaxUploadSizeExceededException;

/**
 * 全局异常处理类
 * @author ANTIA1
 * @date 2021/7/7 23:21
 */

//@ControllerAdvice //@Controller 返回视图
@RestControllerAdvice //@RestController 返回JSON数据...
public class MyGlobalException {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public String customException(MaxUploadSizeExceededException e){
        return "上传文件大小超出限制";
    }
}

01.html

<!DOCTYPE html>
<html lang="zh">
<head>
    
    <title>Title</title>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
  </form>
</body>
</html>

application.properties

# 应用名称
spring.application.name=fileupload
# 应用服务 WEB 访问端口
server.port=8080

# 设置文件最大值
spring.servlet.multipart.max-file-size=1KB

运行结果:

image-20210707232938136

(二)返回页面

MyGlobalException.java

package com.zhuantai.fileupload.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.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理类
 * @author ANTIA1
 * @date 2021/7/7 23:21
 */

@ControllerAdvice //@Controller 返回视图
public class MyGlobalException {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ModelAndView customException(MaxUploadSizeExceededException e) {
        ModelAndView mv = new ModelAndView("zhuantai");
        mv.addObject("error", e.getMessage());
        return mv;
    }
}

01.html

<!DOCTYPE html>
<html lang="zh">
<head>
    
    <title>Title</title>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
  </form>
</body>
</html>

templates/zhuantai.html

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

运行结果:

image-20210707235843351

3.全局数据绑定

MyGlobalData.java

package com.zhuantai.controlleradvice;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局数据绑定
 * @author ANTIA1
 * @date 2021/7/8 0:06
 */
@ControllerAdvice
public class MyGlobalData {

    @ModelAttribute("info")//不定义名称默认为map
    public Map<String,String> myData(){
        Map<String,String> info = new HashMap<>();
        info.put("username","zhuantai");
        info.put("address","antia1.top");
        return info;
    }
}

HelloController.java

package com.zhuantai.controlleradvice;

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

import java.util.Map;

/**
 * @author ANTIA1
 * @date 2021/7/8 0:10
 */
@RestController
public class HelloController {
    @GetMapping("/hello")
    public void hello(Model model){
        Map<String, Object> asMap = model.asMap();
        Map<String,String> info = (Map<String, String>) asMap.get("info");
        for (String s : info.keySet()){
            System.out.println("s = " + s);
        }
    }
}

运行结果:

image-20210708001551475

4.全局数据预处理

MyGlobalData.java

package com.zhuantai.controlleradvice;

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

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

/**
 * 全局数据绑定
 * @author ANTIA1
 * @date 2021/7/8 0:06
 */
@ControllerAdvice
public class MyGlobalData {

    @InitBinder("b")
    public void b(WebDataBinder binder){
        binder.setFieldDefaultPrefix("b.");//设置一个默认的前缀
    }

    @InitBinder("a")
    public void a(WebDataBinder binder){
        binder.setFieldDefaultPrefix("a.");//设置一个默认的前缀
    }
}

BookController.java

package com.zhuantai.controlleradvice;

import com.zhuantai.controlleradvice.model.Author;
import com.zhuantai.controlleradvice.model.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @author ANTIA1
 * @date 2021/7/8 0:18
 */
@Controller
public class  BookController {

    @PostMapping("/book")
    public void addBook(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author){
        System.out.println("book = " + book);
        System.out.println("author = " + author);
    }
}

Book.java

package com.zhuantai.controlleradvice.model;

/**
 * @author ANTIA1
 * @date 2021/7/8 0:17
 */
public class Book {
    private String name;
    private Double price;

    public Book(String name, Double price) {
        this.name = name;
        this.price = 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 +
                '}';
    }
}

Author.java

package com.zhuantai.controlleradvice.model;

/**
 * @author ANTIA1
 * @date 2021/7/8 0:18
 */
public class Author {
    private String name;
    private Integer age;

    public Author(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

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

测试:

image-20210708004053559

运行结果:image-20210708004133459

posted @ 2021-08-02 22:59  ANTIA11  阅读(242)  评论(0编辑  收藏  举报