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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢牛牛_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值