zoukankan      html  css  js  c++  java
  • 【Spring】spring全局异常处理即全局model数据写入

    spring全局异常处理即全局model数据写入

    @ControllerAdvice

    用于全局controller处理

    1.与@ExceptionHandler({ Exception.class })配合使用

    /**
     * @Auther: wxg
     * @Date: 2018/7/24 17:36
     * @Description:Controller全局异常处理
     */
    @ControllerAdvice
    public class ControllerGlobalExceptionHandel {
        @ExceptionHandler(NullPointerException.class)
        @ResponseBody
        public Object handException(NullPointerException e){
            ResponseData responseData = new ResponseData(false,e.getMessage());
            return responseData;
        }
    }
    

    上边这个对所有添加了@RequestMapping的方法进行异常捕获,@ExceptionHandler指定了要捕获的异常类型,可以是多个。

    这样在controller中发生异常时会返回异常信息。

    @ModelAttribute

    可以向model中写入全局数据:

    /**
     * Created by wxg on 2018/7/25 07:55
     */
    @ControllerAdvice
    public class GlobalModelData {
        @ModelAttribute
        public Object globalUser() {
            User user = new User();
            user.setUn("xxx");
            return user;
            /*这里在controller执行前将返回值填充到model中,则可以在model中获取数据*/
        }
    }
    
    @ResponseBody
    @RequestMapping("test")
    public String test(@ModelAttribute User user) {
        //user会在执行前放入model
        return JSONObject.fromObject(user).toString();
    }
    

    可以将登录后的用户信息或者一些配置放进去。

  • 相关阅读:
    在 mac iTerm2 中使用 cmd 终端
    在 jupyter 中添加菜单和自动完成功能
    Bash 和 Zsh 开启 vi-mode
    免密登录和远程执行命令
    图片的筛选
    win10 右键菜单很慢的解决方式
    ssh中的 Connection closed by ***
    NodeJS 获取网页源代码
    在 JSDOM v11 中使用jQuery
    kafaka学习
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286678.html
Copyright © 2011-2022 走看看