【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();
}

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

原文地址:https://www.cnblogs.com/cnsec/p/13286678.html