对web请求的结果进行自动封装 , 对于一些异常,可以用全局异常进行捕获;
1 响应结果自动封装
通常我们业务返回结果处理的时候 , 会进行人为手动对请求的结果的封装成特定的格式 , 这样可以自定义错误码和错误信息 , 但是对于不变的错误码我们要进行多次人为的封装 , 为此可以用下面的操作,下面是Demo , 供学习
1.1 设置返回结果实体与返回枚举结果
1.1.1 设置结果实体类-Result
1 | package xiaoliu.demo; |
###1.1.2 设置枚举类-ResultCode
1 | public enum ResultCode { |
1.2 设置注解和mvc拦截器
1.2.1 设置注解
这里的注解作用是为了判断类上或者方法上是否需要进行请求结果的包装
1 | /** |
1.2.2 设置mvc拦截器
为什么这里使用拦截器 , 不用Filter? 因为Interceptor可以拿到spring框架中的自定义属性 , 而filter不能.
1 | /** |
1.3 将拦截器注入spring
mvc提供了一个接口WebMvcConfigurer 或者使用EnableWebMvc , WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer 接口;
在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现WebMvcConfigurer接口(推荐),方式二继承WebMvcConfigurationSupport类,具体实现可看这篇文章。https://blog.csdn.net/fmwind/article/details/82832758
1 | /** |
1.4 设置响应结果包装
ResponseBodyAdvice 源码中注释
1 | * Allows customizing the response after the execution of an {@code @ResponseBody} or a {@code ResponseEntity} controller method but before the body is written with an {@code HttpMessageConverter}. <p>Implementations may be registered directly with {@code RequestMappingHandlerAdapter} and {@code ExceptionHandlerExceptionResolver} or more likely annotated with {@code @ControllerAdvice} in which case they will be auto-detected by both. |
译文
1 | 允许在执行{@code@ResponseBody}或{@code ResponseEntity}控制器方法之后,但在使用{@code HttpMessageConverter}编写正文之前,自定义响应。<p>实现可以直接用{@code RequestMappingHandlerAdapter}和{@code ExceptionHandlerExceptionResolver}注册,或者更可能用{@code@ControllerAdvice}进行注释,在这种情况下,它们将由这两种方法自动检测。 |
为此使用@ControllerAdvice注解加上ResponseBodyAdvice< T >实现对响应结果的封装
1 | /** |
注意: 如果业务的返回类型是String类型 , 源码中HttpMessageConverter 会将结果解析为字符串解析器 , 而结果不转为字符串 , 就会出现类型转化异常
1.5 全局异常拦截
1 | /** |
2 Demo
1 | /** |