使用 @restcontrolleradvice 的主要场景包括:
- 全局异常处理:处理所有控制器中抛出的未捕获异常。
 - 数据校验失败处理:处理 bean validation 校验失败的情况。
 - 自定义响应:统一定义响应格式或错误信息。
 
@restcontrolleradvice 注解的类通常与以下组件结合使用:
@exceptionhandler:用于处理特定的异常类型。@responsestatus:用于定义异常的http状态。@exceptionhandler方法可以访问异常对象、请求对象(webrequest)、响应对象等,以构造合适的响应。
以下是一个简单的示例,演示如何使用 @restcontrolleradvice:
java
import org.springframework.web.bind.annotation.restcontrolleradvice;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.http.httpstatus;
import org.springframework.web.servlet.mvc.method.annotation.responseentityexceptionhandler;
@restcontrolleradvice
public class globalexceptionhandler extends responseentityexceptionhandler {
    // 处理自定义异常
    @exceptionhandler(customexception.class)
    public responseentity<string> handlecustomexception(customexception ex, webrequest request) {
        // 构造错误信息
        string error = "an error occurred: " + ex.getmessage();
        return new responseentity<>(error, httpstatus.bad_request);
    }
    // 可以添加更多的异常处理方法
}在这个示例中,globalexceptionhandler 类使用 @restcontrolleradvice 注解标记,使其成为全局异常处理器。类中的 handlecustomexception 方法使用 @exceptionhandler 注解标记,用于处理 customexception 类型的异常。
使用 @restcontrolleradvice 可以集中处理异常,使控制器代码更简洁、更专注于业务逻辑,同时提高异常处理的可维护性。
一个模拟权限校验的案例
首先自定义一个权限不够的异常
public class permissionexception extends exception{
    // 构造函数
    public permissionexception() {
        super();
    }
    public permissionexception(string message) {
        super(message);
    }
    public permissionexception(string message, throwable cause) {
        super(message, cause);
    }
    public permissionexception(throwable cause) {
        super(cause);
    }
}然后用注解的方式写一个异常处理类
@restcontrolleradvice
public class permissionexceptionhandler {
    @exceptionhandler(permissionexception.class)
    public map handlemycustomexception(permissionexception ex) {
        map<string, string> msg = new hashmap<>();
        msg.put("status","500");
        msg.put("msg","错误,没有权限");
        return  msg;
    }
}然后写一个处理权限校验的拦截器
/*
* prehandle在执行处理器方法之前执行
* posthandle在执行处理器方法之后执行
* aftercompletion在这次请求完成后执行
* */
@component
public class permissioninterceptor implements handlerinterceptor {
    @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
        string auth = request.getparameter("auth");
        system.out.println(auth);
        if ("0".equals(auth)){
            throw new permissionexception();
        }
        //返回true放行,返回false不放行
        return true;
    }
    @override
    public void posthandle(httpservletrequest request, httpservletresponse response, object handler, modelandview modelandview) throws exception {
        handlerinterceptor.super.posthandle(request, response, handler, modelandview);
    }
    @override
    public void aftercompletion(httpservletrequest request, httpservletresponse response, object handler, exception ex) throws exception {
        handlerinterceptor.super.aftercompletion(request, response, handler, ex);
    }
}然后把拦截器注册到spring中
@configuration
public class webconfig implements webmvcconfigurer {
    @autowired
    private handlerinterceptor permissioninterceptor;
    @override
    public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(permissioninterceptor)
                .addpathpatterns("/**") // 拦截所有请求
                .excludepathpatterns("/ignorethis"); // 排除不需要拦截的请求
    }
}然后你请求http://localhost:8080/user/1?auth=1
你会发现auth=1的时候拦截器放行
auth=0的时候会被拦截器拦截,并且抛出我们自定义的异常,然后自定义异常会被我们写的异常处理器监听到,最终给客户端返回没有权限
到此这篇关于springmvc @restcontrolleradvice注解使用方式的文章就介绍到这了,更多相关springmvc @restcontrolleradvice注解内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
            
                                            
发表评论