SpringBoot统一功能处理(一)https://developer.aliyun.com/article/1393197
从上述源码可以看出在开始执行 Controller 之前,会先调用 预处理方法 applyPreHandle,而applyPreHandle 方法的实现源码如下:
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception { for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex = i++) { // 获取项⽬中使⽤的拦截器 HandlerInterceptor HandlerInterceptor interceptor = (HandlerInterceptor)this.interceptorList.get(i); if (!interceptor.preHandle(request, response, this.handler)) { this.triggerAfterCompletion(request, response, (Exception)null); return false; } } return true; }
从上述源码可以看出,在 applyPreHandle 中会获取所有的拦截器 HandlerInterceptor 并执行拦截器中的 preHandle 方法,这样就和咱们前面定义的拦截器对应上了,如下图所示:
此时用户登录权限的验证方法就会执行,这就是拦截器的实现原理。
二、统⼀异常处理🍭
Ⅰ、实现🍓
统一异常处理使用的是 @ControllerAdvice + @ExceptionHandler 来实现的,@ControllerAdvice 表示控制器通知类,@ExceptionHandler 是异常处理器,两个结合表示当出现异常的时候执行某个通知, 也就是执行某个方法事件,具体实现代码如下:
package com.example.demo.config; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; @ControllerAdvice @ResponseBody public class MyExHandler { /** * 拦截所有的空指针异常,进行统一的数据返回 */ @ExceptionHandler(NullPointerException.class) public HashMap<String, Object> nullException(NullPointerException e) { HashMap<String, Object> result = new HashMap<>(); result.put("code", "-1"); result.put("msg", "空指针异常:" + e.getMessage()); // 错误码的描述信息 result.put("data", null); return result; } @ExceptionHandler(Exception.class)//保底的默认异常 public HashMap<String, Object> exception(Exception e) { HashMap<String, Object> result = new HashMap<>(); result.put("code", "-1"); result.put("msg", "异常:" + e.getMessage()); // 错误码的描述信息 result.put("data", null); return result; } }
Ⅱ、添加异常🍓
UserController
@RequestMapping("/login") public String login() { Object obj = null; obj.hashCode(); System.out.println("执行了 login~"); return "login~"; } @RequestMapping("/reg") public String reg() { int num = 10 / 0; System.out.println("执行了 reg~"); return "reg~"; }
Ⅲ、启动程序:🍓
login:
reg:
方法名和返回值可以自定义,其中最重要是 @ExceptionHandler(Exception.class) 注解。
以上方法表示,如果出现了异常就返回给前端⼀个 HashMap 的对象,其中包含的字段如代码中定义的那样。 我们可以针对不同的异常,返回不同的结果。
三、统一数据返回格式🍭
1.创建一个类,并添加 @ControllerAdvice
2.实现ResponseBodyAdvice接口,并重写supports和beforeBodywrite (统一对象就是此方法中实现的)
1、为什么需要统一数据返回格式?🍉
统一数据返回格式的优点有很多,比如以下几个:
- 方便前端程序员更好的接收和解析后端数据接口返回的数据。
- 降低前端程序员和后端程序员的沟通成本,按照某个格式实现就行了,因为所有接口都是这样返回的。
- 有利于项目统⼀数据的维护和修改。
- 有利于后端技术部门的统⼀规范的标准制定,不会出现稀奇古怪的返回内容。
2、统一数据返回格式的实现🍉
Ⅰ、实现🍓
统⼀的数据返回格式可以使用 @ControllerAdvice + ResponseBodyAdvice 的方式实现。
java
复制代码
package com.example.demo.config; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import java.util.HashMap; @ControllerAdvice public class ResponseAdvice implements ResponseBodyAdvice { @Autowired private ObjectMapper objectMapper; /** * 此方法返回 true 则执行下面 beforeBodyWrite 方法 * 反之则不执行 */ @Override public boolean supports(MethodParameter returnType, Class converterType) { return true; } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { HashMap<String, Object> result = new HashMap<>(); result.put("code", 200); result.put("msg", ""); result.put("data", body); // 需要特殊处理,因为 String 在转换的时候会报错 if (body instanceof String) { try { return objectMapper.writeValueAsString(result); } catch (JsonProcessingException e) { e.printStackTrace(); } } return result; } }
如果没有对Sting进行特殊处理,就会有异常出现:
Ⅱ、添加实现类🍓
UserController
@RequestMapping("/getnum") public Integer getNumber() { return new Random().nextInt(10); } @RequestMapping("/getuser") public String getUser() { System.out.println("执行了 get User~"); return "get user"; }
Ⅲ、启动程序🍓
Ⅳ、总结🍓
上面只是以一种简单的方式来向大家介绍如何去统一数据返回格式,在实际工作中并不会这样去使用
而是将统⼀的返回格式(包含:status、data、msg 字段)进行封装成一个类:
根据不同操作成功和操作失败的情况,重写了不同的方法:
package com.example.demo.common; import lombok.Data; import java.io.Serializable; /** * 统一数据格式返回 */ @Data public class AjaxResult implements Serializable {//支持序列化 // 状态码 private Integer code; // 状态码描述信息 private String msg; // 返回的数据 private Object data; /** * 操作成功返回的结果,需要 data */ public static AjaxResult success(Object data) { AjaxResult result = new AjaxResult(); result.setCode(200); result.setMsg(""); result.setData(data); return result; } //重载success public static AjaxResult success(int code, Object data) { AjaxResult result = new AjaxResult(); result.setCode(code); result.setMsg(""); result.setData(data); return result; } public static AjaxResult success(int code, String msg, Object data) { AjaxResult result = new AjaxResult(); result.setCode(code); result.setMsg(msg); result.setData(data); return result; } /** * 返回失败结果 */ public static AjaxResult fail(int code, String msg) { AjaxResult result = new AjaxResult(); result.setCode(code); result.setMsg(msg); result.setData(null); return result; } public static AjaxResult fail(int code, String msg, Object data) { AjaxResult result = new AjaxResult(); result.setCode(code); result.setMsg(msg); result.setData(data); return result; } }






