微人事第四天:@ControllerAdvice的两种种用法

1.处理全局异常
根据文件上传的代码(在我博客的前一章),现在在配置文件中修改文件上传的大小

spring.servlet.multipart.max-file-size=1KB

访问http://localhost:8080/index3.html 上传一张图片显示:
在这里插入图片描述
可以得知上传的文件大小超过了1KB,但是现在的提示很不友好。我们现在要来自定义异常信息。
创建自定义异常类:MyCustomException

package org.javaboy.fileuoload;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
public class MyCustomException {

    //知道要拦截的异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public void myexception(MaxUploadSizeExceededException e, HttpServletResponse resp) throws IOException {
    	//预防出现乱码
        resp.setContentType("text/html;charset=utf-8");
        //给前端传送消息
        PrintWriter out = resp.getWriter();
        out.write("上传文件大小超出限制");
        out.flush();
        out.close();
    }
}

现在再去上传文件显示:
在这里插入图片描述
@ControllerAdvice可以处理全局异常问题,使得springboot报出的异常更加友好。

2.预设全局数据
@ControllerAdvice中定义的数据,在别的controller中也可以获取得到
先定义全局数据:

package org.javaboy.controlleradvice;

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 GlobalData {

    @ModelAttribute(value = "info")
    public Map<String,Object> mydata() {
        Map<String,Object> map = new HashMap<>();
        map.put("name","javaboy");
        map.put("address", "www.javaboy.org");
        return map;
    }
}

这里可以把info看成是key,map看成是value,整合起来就是Map嵌套Map的结构。
现在定义一个controller来获取全局数据

package org.javaboy.controlleradvice;

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

import java.util.Map;
import java.util.Set;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        //将获取的model转换为map
        Map<String, Object> map = model.asMap();
        //返回map中所有key值的列表
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            System.out.println(key + ":" + map.get(key));
        }
        return "hello";
    }
}

原理:先拿到model,把model转换成Map,然后拿出Map中所有的key值。然后遍历key值获取value。

启动之后打印出:

info:{address=www.javaboy.org, name=javaboy}

发布了287 篇原创文章 · 获赞 24 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41998938/article/details/104000766
今日推荐