欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解SpringBoot中的統(tǒng)一功能處理的實(shí)現(xiàn)

 更新時(shí)間:2023年01月28日 17:03:52   作者:yyhgo_  
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何實(shí)現(xiàn)統(tǒng)一功能處理,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)或工作有一定借鑒價(jià)值,需要的可以參考一下

前言

接下來(lái)是 Spring Boot 統(tǒng)?功能處理模塊了,也是 AOP 的實(shí)戰(zhàn)環(huán)節(jié),要實(shí)現(xiàn)的課程?標(biāo)有以下 3 個(gè):

  • 統(tǒng)??戶(hù)登錄權(quán)限驗(yàn)證
  • 統(tǒng)?數(shù)據(jù)格式返回
  • 統(tǒng)?異常處理

接下我們?個(gè)?個(gè)來(lái)看。

一、用戶(hù)登錄權(quán)限效驗(yàn)

?戶(hù)登錄權(quán)限的發(fā)展從之前每個(gè)?法中??驗(yàn)證?戶(hù)登錄權(quán)限,到現(xiàn)在統(tǒng)?的?戶(hù)登錄驗(yàn)證處理,它是?個(gè)逐漸完善和逐漸優(yōu)化的過(guò)程。

1.1 最初的用戶(hù)登錄驗(yàn)證

我們先來(lái)回顧?下最初?戶(hù)登錄驗(yàn)證的實(shí)現(xiàn)?法:

@RestController
@RequestMapping("/user")
public class UserController {
    /**
     * 某?法 1
     */
    @RequestMapping("/m1")
    public Object method(HttpServletRequest request) {
        // 有 session 就獲取,沒(méi)有不會(huì)創(chuàng)建
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("userinfo") != null) {
            // 說(shuō)明已經(jīng)登錄,業(yè)務(wù)處理
            return true;
        } else {
            // 未登錄
            return false;
        }
    }
    /**
     * 某?法 2
     */
    @RequestMapping("/m2")
    public Object method2(HttpServletRequest request) {
        // 有 session 就獲取,沒(méi)有不會(huì)創(chuàng)建
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("userinfo") != null) {
            // 說(shuō)明已經(jīng)登錄,業(yè)務(wù)處理
            return true;
        } else {
            // 未登錄
            return false;
        }
    }
    // 其他?法...
}

從上述代碼可以看出,每個(gè)?法中都有相同的?戶(hù)登錄驗(yàn)證權(quán)限,它的缺點(diǎn)是:

  • 每個(gè)?法中都要單獨(dú)寫(xiě)?戶(hù)登錄驗(yàn)證的?法,即使封裝成公共?法,也?樣要傳參調(diào)?和在?法中進(jìn)?判斷。
  • 添加控制器越多,調(diào)??戶(hù)登錄驗(yàn)證的?法也越多,這樣就增加了后期的修改成本和維護(hù)成本。
  • 這些?戶(hù)登錄驗(yàn)證的?法和接下來(lái)要實(shí)現(xiàn)的業(yè)務(wù)?何沒(méi)有任何關(guān)聯(lián),但每個(gè)?法中都要寫(xiě)?遍。

所以提供?個(gè)公共的 AOP ?法來(lái)進(jìn)?統(tǒng)?的?戶(hù)登錄權(quán)限驗(yàn)證迫在眉睫。

1.2 Spring AOP 用戶(hù)統(tǒng)一登錄驗(yàn)證的問(wèn)題

說(shuō)到統(tǒng)?的?戶(hù)登錄驗(yàn)證,我們想到的第?個(gè)實(shí)現(xiàn)?案是 Spring AOP 前置通知或環(huán)繞通知來(lái)實(shí)現(xiàn),具體實(shí)現(xiàn)代碼如下:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class UserAspect {
    // 定義切點(diǎn)?法 controller 包下、?孫包下所有類(lèi)的所有?法
    @Pointcut("execution(* com.example.demo.controller..*.*(..))")
    public void pointcut(){ }
    // 前置?法
    @Before("pointcut()")
    public void doBefore(){

    }

    // 環(huán)繞?法
    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint){
        Object obj = null;
        System.out.println("Around ?法開(kāi)始執(zhí)?");
        try {
            // 執(zhí)?攔截?法
            obj = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        System.out.println("Around ?法結(jié)束執(zhí)?");
        return obj;
    }
}

如果要在以上 Spring AOP 的切?中實(shí)現(xiàn)?戶(hù)登錄權(quán)限效驗(yàn)的功能,有以下兩個(gè)問(wèn)題:

1.沒(méi)辦法獲取到 HttpSession 對(duì)象。

2.我們要對(duì)?部分?法進(jìn)?攔截,?另?部分?法不攔截,如注冊(cè)?法和登錄?法是不攔截的,這樣的話(huà)排除?法的規(guī)則很難定義,甚?沒(méi)辦法定義。

那這樣如何解決呢?

1.3 Spring 攔截器

對(duì)于以上問(wèn)題 Spring 中提供了具體的實(shí)現(xiàn)攔截器:HandlerInterceptor,攔截器的實(shí)現(xiàn)分為以下兩個(gè)步驟:

1.創(chuàng)建?定義攔截器,實(shí)現(xiàn) HandlerInterceptor 接?的 preHandle(執(zhí)?具體?法之前的預(yù)處理)?法。

2.將?定義攔截器加? WebMvcConfigurer 的 addInterceptors ?法中。

具體實(shí)現(xiàn)如下。

補(bǔ)充 過(guò)濾器:

過(guò)濾器是Web容器提供的。觸發(fā)的時(shí)機(jī)比攔截器更靠前,Spring 初始化前就執(zhí)行了,所以并不能處理用戶(hù)登錄權(quán)限效驗(yàn)等問(wèn)題。

1.3.1 準(zhǔn)備工作

package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @RequestMapping("/login")
    public boolean login(HttpServletRequest request,
                         String username, String password) {
//        // 1.非空判斷
//        if (username != null && username != "" &&
//                password != null && username != "") {
//            // 2.驗(yàn)證用戶(hù)名和密碼是否正確
//        }

        // 1.非空判斷
        if (StringUtils.hasLength(username) && StringUtils.hasLength(password)) {
            // 2.驗(yàn)證用戶(hù)名和密碼是否正確
            if ("admin".equals(username) && "admin".equals(password)) {
                // 登錄成功
                HttpSession session = request.getSession();
                session.setAttribute("userinfo", "admin");
                return true;
            } else {
                // 用戶(hù)名或密碼輸入錯(cuò)誤
                return false;
            }
        }
        return false;
    }

    @RequestMapping("/getinfo")
    public String getInfo() {
        log.debug("執(zhí)行了 getinfo 方法");
        return "執(zhí)行了 getinfo 方法";
    }

    @RequestMapping("/reg")
    public String reg() {
        log.debug("執(zhí)行了 reg 方法");
        return "執(zhí)行了 reg 方法";
    }

}

1.3.2 自定義攔截器

接下來(lái)使?代碼來(lái)實(shí)現(xiàn)?個(gè)?戶(hù)登錄的權(quán)限效驗(yàn),?定義攔截器是?個(gè)普通類(lèi),具體實(shí)現(xiàn)代碼如下:

package com.example.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登錄攔截器
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 登錄判斷業(yè)務(wù)
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute("userinfo") != null) {
            return true;
        }
        log.error("當(dāng)前用戶(hù)沒(méi)有訪(fǎng)問(wèn)權(quán)限");
        response.setStatus(401);
        return false;
    }
}

返回 boolean 類(lèi)型。

相當(dāng)于一層安保:

為 false 則不能繼續(xù)往下執(zhí)行;為 true 則可以。

1.3.3 將自定義攔截器加入到系統(tǒng)配置

將上?步中的?定義攔截器加?到系統(tǒng)配置信息中,具體實(shí)現(xiàn)代碼如下:

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration // 一定不要忘記
public class MyConfig implements WebMvcConfigurer {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**") // 攔截所有請(qǐng)求
                .excludePathPatterns("/user/login") // 排除不攔截的 url
//                .excludePathPatterns("/**/*.html")
//                .excludePathPatterns("/**/*.js")
//                .excludePathPatterns("/**/*.css")
                .excludePathPatterns("/user/reg"); // 排除不攔截的 url
    }
}

或者:

package com.example.demo.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class AppConfig implements WebMvcConfigurer {

    // 不攔截的 url 集合
    List<String> excludes = new ArrayList<String>() {{
        add("/**/*.html");
        add("/js/**");
        add("/editor.md/**");
        add("/css/**");
        add("/img/**"); // 放行 static/img 下的所有文件
        add("/user/login"); // 放行登錄接口
        add("/user/reg"); // 放行注冊(cè)接口
        add("/art/detail"); // 放行文章詳情接口
        add("/art/list"); // 放行文章分頁(yè)列表接口
        add("/art/totalpage"); // 放行文章分頁(yè)總頁(yè)數(shù)接口
    }};

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 配置攔截器
        InterceptorRegistration registration =
                registry.addInterceptor(loginInterceptor);
        registration.addPathPatterns("/**");
        registration.excludePathPatterns(excludes);
    }
}

如果不注入對(duì)象的話(huà),addInterceptor() 的參數(shù)也可以直接 new 一個(gè)對(duì)象:

@Configuration // 一定不要忘記
public class MyConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**") // 攔截所有請(qǐng)求
                .excludePathPatterns("/user/login") // 排除不攔截的 url
//                .excludePathPatterns("/**/*.html")
//                .excludePathPatterns("/**/*.js")
//                .excludePathPatterns("/**/*.css")
//                .excludePathPatterns("/**/*.jpg")
//                .excludePathPatterns("/**/login")
                .excludePathPatterns("/user/reg"); // 排除不攔截的 url
    }
}

其中:

addPathPatterns:表示需要攔截的 URL,“**”表示攔截任意?法(也就是所有?法)。

excludePathPatterns:表示需要排除的 URL。

說(shuō)明:以上攔截規(guī)則可以攔截此項(xiàng)?中的使? URL,包括靜態(tài)?件 (圖??件、JS 和 CSS 等?件)。

1.4 攔截器實(shí)現(xiàn)原理

正常情況下的調(diào)?順序:

然?有了攔截器之后,會(huì)在調(diào)? Controller 之前進(jìn)?相應(yīng)的業(yè)務(wù)處理,執(zhí)?的流程如下圖所示:

1.4.1 實(shí)現(xiàn)原理源碼分析

所有的 Controller 執(zhí)?都會(huì)通過(guò)?個(gè)調(diào)度器 DispatcherServlet 來(lái)實(shí)現(xiàn),這?點(diǎn)可以從 Spring Boot 控制臺(tái)的打印信息看出,如下圖所示:

?所有?法都會(huì)執(zhí)? DispatcherServlet 中的 doDispatch 調(diào)度?法,doDispatch 源碼如下:

    protected void doDispatch(HttpServletRequest request, HttpServletResponse
            response) throws Exception {
        HttpServletRequest processedRequest = request;
        HandlerExecutionChain mappedHandler = null;
        boolean multipartRequestParsed = false;
        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
        try {
            try {
                ModelAndView mv = null;
                Object dispatchException = null;
                try {
                    processedRequest = this.checkMultipart(request);
                    multipartRequestParsed = processedRequest != request;
                    mappedHandler = this.getHandler(processedRequest);
                    if (mappedHandler == null) {
                        this.noHandlerFound(processedRequest, response);
                        return;
                    }
                    HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.g
                            etHandler());
                    String method = request.getMethod();
                    boolean isGet = HttpMethod.GET.matches(method);
                    if (isGet || HttpMethod.HEAD.matches(method)) {
                        long lastModified = ha.getLastModified(request, mapped
                                Handler.getHandler());
                        if ((new ServletWebRequest(request, response)).checkNo
                        tModified(lastModified) && isGet) {
                            return;
                        }
                    }
                    // 調(diào)?預(yù)處理【重點(diǎn)】
                    if (!mappedHandler.applyPreHandle(processedRequest, respon
                            se)) {
                        return;
                    }
                    // 執(zhí)? Controller 中的業(yè)務(wù)
                    mv = ha.handle(processedRequest, response, mappedHandler.g
                            etHandler());
                    if (asyncManager.isConcurrentHandlingStarted()) {
                        return;
                    }
                    this.applyDefaultViewName(processedRequest, mv);
                    mappedHandler.applyPostHandle(processedRequest, response,
                            mv);
                } catch (Exception var20) {
                    dispatchException = var20;
                } catch (Throwable var21) {
                    dispatchException = new NestedServletException("Handler di
                            spatch failed", var21);
                }
                this.processDispatchResult(processedRequest, response, mappedH
                        andler, mv, (Exception)dispatchException);
            } catch (Exception var22) {
                this.triggerAfterCompletion(processedRequest, response, mapped
                        Handler, var22);
            } catch (Throwable var23) {
                this.triggerAfterCompletion(processedRequest, response, mapped
                        Handler, new NestedServletException("Handler processing failed", var23));
            }
        } finally {
            if (asyncManager.isConcurrentHandlingStarted()) {
                if (mappedHandler != null) {
                    mappedHandler.applyAfterConcurrentHandlingStarted(processe
                            dRequest, response);
                }
            } else if (multipartRequestParsed) {
                this.cleanupMultipart(processedRequest);
            }
        }
    }

從上述源碼可以看出在開(kāi)始執(zhí)? Controller 之前,會(huì)先調(diào)? 預(yù)處理?法 applyPreHandle,?applyPreHandle ?法的實(shí)現(xiàn)源碼如下:

    boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        for(int i = 0; i < this.interceptorList.size(); this.interceptorIndex
                = i++) {
            // 獲取項(xiàng)?中使?的攔截器 HandlerInterceptor
            HandlerInterceptor interceptor = (HandlerInterceptor)this.intercep
            torList.get(i);
            if (!interceptor.preHandle(request, response, this.handler)) {
                this.triggerAfterCompletion(request, response, (Exception)null
                );
                return false;
            }
        }
        return true;
    }

從上述源碼可以看出,在 applyPreHandle 中會(huì)獲取所有的攔截器 HandlerInterceptor 并執(zhí)?攔截器中的 preHandle ?法,這樣就會(huì)咱們前?定義的攔截器對(duì)應(yīng)上了,如下圖所示:

此時(shí)?戶(hù)登錄權(quán)限的驗(yàn)證?法就會(huì)執(zhí)?,這就是攔截器的實(shí)現(xiàn)原理。

1.4.2 攔截器小結(jié)

通過(guò)上?的源碼分析,我們可以看出,Spring 中的攔截器也是通過(guò)動(dòng)態(tài)代理和環(huán)繞通知的思想實(shí)現(xiàn)的,?體的調(diào)?流程如下:

1.5 擴(kuò)展:統(tǒng)一訪(fǎng)問(wèn)前綴添加

所有請(qǐng)求地址添加 api 前綴:

    @Configuration
    public class AppConfig implements WebMvcConfigurer {
        // 所有的接?添加 api 前綴
        @Override
        public void configurePathMatch(PathMatchConfigurer configurer) {
            configurer.addPathPrefix("api", c -> true);
        }
    }

其中第?個(gè)參數(shù)是?個(gè)表達(dá)式,設(shè)置為 true 表示啟動(dòng)前綴。

二、統(tǒng)一異常處理

統(tǒng)?異常處理使?的是 @ControllerAdvice + @ExceptionHandler 來(lái)實(shí)現(xiàn)的,@ControllerAdvice 表示控制器通知類(lèi),@ExceptionHandler 是異常處理器,兩個(gè)結(jié)合表示當(dāng)出現(xiàn)異常的時(shí)候執(zhí)?某個(gè)通知,也就是執(zhí)?某個(gè)?法事件,具體實(shí)現(xiàn)代碼如下:

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;

/**
 * 統(tǒng)一處理異常
 */
@ControllerAdvice
public class ErrorAdive {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public HashMap<String, Object> exceptionAdvie(Exception e) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", "-1");
        result.put("msg", e.getMessage());
        return result;
    }

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public HashMap<String, Object> arithmeticAdvie(ArithmeticException e) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", "-2");
        result.put("msg", e.getMessage());
        return result;
    }

}

方法名和返回值可以?定義,重要的是 @ControllerAdvice 和 @ExceptionHandler 注解。

以上?法表示,如果出現(xiàn)了異常就返回給前端?個(gè) HashMap 的對(duì)象,其中包含的字段如代碼中定義的那樣。

我們可以針對(duì)不同的異常,返回不同的結(jié)果,?以下代碼所示:

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 ExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public Object exceptionAdvice(Exception e) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("success", -1);
        result.put("message", "總的異常信息:" + e.getMessage());
        result.put("data", null);
        return result;
    }
    @ExceptionHandler(NullPointerException.class)
    public Object nullPointerexceptionAdvice(NullPointerException e) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("success", -1);
        result.put("message", "空指針異常:" + e.getMessage());
        result.put("data", null);
        return result;
    }
}

當(dāng)有多個(gè)異常通知時(shí),匹配順序?yàn)楫?dāng)前類(lèi)及其子類(lèi)向上依次匹配,案例演示:

在 UserController 中設(shè)置?個(gè)空指針異常,實(shí)現(xiàn)代碼如下:

    @RestController
    @RequestMapping("/u")
    public class UserController {
        @RequestMapping("/index")
        public String index() {
            Object obj = null;
            int i = obj.hashCode();
            return "Hello,User Index.";
        }
    }

以上程序的執(zhí)?結(jié)果如下:

此時(shí)若出現(xiàn)異常就不會(huì)報(bào)錯(cuò)了,代碼會(huì)繼續(xù)執(zhí)行,但是會(huì)把自定義的異常信息返回給前端!

統(tǒng)一完數(shù)據(jù)返回格式后:

package com.example.demo.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 異常類(lèi)的統(tǒng)一處理
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public Object exceptionAdvice(Exception e) {
        return AjaxResult.fail(-1, e.getMessage());
    }
    
}

統(tǒng)一異常處理不用配置路徑,是攔截整個(gè)項(xiàng)目中的所有異常。

三、統(tǒng)一數(shù)據(jù)返回格式

3.1 為什么需要統(tǒng)一數(shù)據(jù)返回格式

統(tǒng)?數(shù)據(jù)返回格式的優(yōu)點(diǎn)有很多,比如以下幾個(gè):

  • ?便前端程序員更好的接收和解析后端數(shù)據(jù)接?返回的數(shù)據(jù)。
  • 降低前端程序員和后端程序員的溝通成本,按照某個(gè)格式實(shí)現(xiàn)就?了,因?yàn)樗薪?都是這樣返回的。
  • 有利于項(xiàng)?統(tǒng)?數(shù)據(jù)的維護(hù)和修改。
  • 有利于后端技術(shù)部?的統(tǒng)?規(guī)范的標(biāo)準(zhǔn)制定,不會(huì)出現(xiàn)稀奇古怪的返回內(nèi)容。

3.2 統(tǒng)一數(shù)據(jù)返回格式的實(shí)現(xiàn)

統(tǒng)?的數(shù)據(jù)返回格式可以使用 @ControllerAdvice + ResponseBodyAdvice接口 的方式實(shí)現(xiàn),具體實(shí)現(xiàn)代碼如下:

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.ResponseBodyA
dvice;

import java.util.HashMap;

/**
 * 統(tǒng)一返回?cái)?shù)據(jù)的處理
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    /**
     * 內(nèi)容是否需要重寫(xiě)(通過(guò)此?法可以選擇性部分控制器和?法進(jìn)?重寫(xiě))
     * 返回 true 表示重寫(xiě)
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterTyp
e) {
        return true;
    }
    /**
     * ?法返回之前調(diào)?此?法
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpR
                                          equest request,
                                  ServerHttpResponse response) {
        // 構(gòu)造統(tǒng)?返回對(duì)象
        HashMap<String, Object> result = new HashMap<>();
        result.put("state", 1);
        result.put("msg", "");
        result.put("data", body);
        return result;
    }
}

統(tǒng)一處理后,此時(shí)所有返回的都是 json 格式的數(shù)據(jù)了。

若方法的返回類(lèi)型為 String,統(tǒng)一數(shù)據(jù)返回格式封裝后,返回會(huì)報(bào)錯(cuò)???

轉(zhuǎn)換器的問(wèn)題,解決方案:

實(shí)際開(kāi)發(fā)中這種統(tǒng)一數(shù)據(jù)返回格式的方式并不常用。因?yàn)樗鼤?huì)將所有返回都再次進(jìn)行封裝,過(guò)于霸道了 ~

而通常我們會(huì)寫(xiě)一個(gè)統(tǒng)一封裝的類(lèi),讓程序猿在返回時(shí)統(tǒng)一返回這個(gè)類(lèi) (軟性約束),例如:

package com.example.demo.common;

import java.util.HashMap;

/**
 * 自定義的統(tǒng)一返回對(duì)象
 */
public class AjaxResult {
    /**
     * 業(yè)務(wù)執(zhí)行成功時(shí)進(jìn)行返回的方法
     *
     * @param data
     * @return
     */
    public static HashMap<String, Object> success(Object data) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "");
        result.put("data", data);
        return result;
    }

    /**
     * 業(yè)務(wù)執(zhí)行成功時(shí)進(jìn)行返回的方法
     *
     * @param data
     * @return
     */
    public static HashMap<String, Object> success(String msg, Object data) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", msg);
        result.put("data", data);
        return result;
    }

    /**
     * 業(yè)務(wù)執(zhí)行失敗返回的數(shù)據(jù)格式
     *
     * @param code
     * @param msg
     * @return
     */
    public static HashMap<String, Object> fail(int code, String msg) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", "");
        return result;
    }

    /**
     * 業(yè)務(wù)執(zhí)行失敗返回的數(shù)據(jù)格式
     *
     * @param code
     * @param msg
     * @return
     */
    public static HashMap<String, Object> fail(int code, String msg, Object data) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", data);
        return result;
    }
}

同時(shí)搭配統(tǒng)一數(shù)據(jù)返回格式:

package com.example.demo.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
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;

/**
 * 統(tǒng)一數(shù)據(jù)返回封裝
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof HashMap) { // 本身已經(jīng)是封裝好的對(duì)象
            return body;
        }
        if (body instanceof String) { // 返回類(lèi)型是 String(特殊)
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        return AjaxResult.success(body);
    }
}

3.3 @ControllerAdvice 源碼分析(了解)

通過(guò)對(duì) @ControllerAdvice 源碼的分析我們可以知道上?統(tǒng)?異常和統(tǒng)?數(shù)據(jù)返回的執(zhí)?流程,我們先從 @ControllerAdvice 的源碼看起,點(diǎn)擊 @ControllerAdvice 實(shí)現(xiàn)源碼如下:

從上述源碼可以看出 @ControllerAdvice 派?于 @Component 組件,?所有組件初始化都會(huì)調(diào)用 InitializingBean 接?。

所以接下來(lái)我們來(lái)看 InitializingBean 有哪些實(shí)現(xiàn)類(lèi)?在查詢(xún)的過(guò)程中我們發(fā)現(xiàn)了,其中 Spring MVC中的實(shí)現(xiàn)?類(lèi)是 RequestMappingHandlerAdapter,它??有?個(gè)?法 afterPropertiesSet() ?法,表示所有的參數(shù)設(shè)置完成之后執(zhí)?的?法,如下圖所示:

?這個(gè)?法中有?個(gè) initControllerAdviceCache ?法,查詢(xún)此?法的源碼如下:

我們發(fā)現(xiàn)這個(gè)?法在執(zhí)?是會(huì)查找使?所有的 @ControllerAdvice 類(lèi),這些類(lèi)會(huì)被容器中,但發(fā)?某個(gè)事件時(shí),調(diào)?相應(yīng)的 Advice ?法,?如返回?cái)?shù)據(jù)前調(diào)?統(tǒng)?數(shù)據(jù)封裝,?如發(fā)?異常是調(diào)?異常的 Advice ?法實(shí)現(xiàn)。

以上就是詳解SpringBoot中的統(tǒng)一功能處理的實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot統(tǒng)一功能處理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java排序的那些事之sort方法的使用詳解

    Java排序的那些事之sort方法的使用詳解

    sort方法用于對(duì)數(shù)組的元素進(jìn)行排序。排序順序可以是字母或數(shù)字,并按升序或降序。默認(rèn)排序順序?yàn)榘醋帜干?,?dāng)數(shù)字是按字母順序排列時(shí)"40"將排在"5"前面。使用數(shù)字排序,你必須通過(guò)一個(gè)函數(shù)作為參數(shù)來(lái)調(diào)用。這些說(shuō)起來(lái)可能很難理解,你可以通過(guò)本篇文章進(jìn)一步了解它
    2021-09-09
  • 淺談如何優(yōu)雅地停止Spring Boot應(yīng)用

    淺談如何優(yōu)雅地停止Spring Boot應(yīng)用

    這篇文章主要介紹了淺談如何優(yōu)雅地停止Spring Boot應(yīng)用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • Java 泛型 Generic機(jī)制實(shí)例詳解

    Java 泛型 Generic機(jī)制實(shí)例詳解

    這篇文章主要為大家介紹了Java 泛型 Generic機(jī)制實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • 詳解SpringBoot如何統(tǒng)一后端返回格式

    詳解SpringBoot如何統(tǒng)一后端返回格式

    今天我們來(lái)聊一聊在基于SpringBoot前后端分離開(kāi)發(fā)模式下,如何友好的返回統(tǒng)一的標(biāo)準(zhǔn)格式以及如何優(yōu)雅的處理全局異常,感興趣的可以了解一下
    2021-07-07
  • springboot后端存儲(chǔ)富文本內(nèi)容的思路與步驟(含圖片內(nèi)容)

    springboot后端存儲(chǔ)富文本內(nèi)容的思路與步驟(含圖片內(nèi)容)

    在所有的編輯器中,大概最受歡迎的就是富文本編輯器和MarkDown編輯器了,下面這篇文章主要給大家介紹了關(guān)于springboot后端存儲(chǔ)富文本內(nèi)容的思路與步驟的相關(guān)資料,需要的朋友可以參考下
    2023-04-04
  • SpringBoot+MyBatis實(shí)現(xiàn)MD5加密數(shù)據(jù)庫(kù)用戶(hù)密碼的方法

    SpringBoot+MyBatis實(shí)現(xiàn)MD5加密數(shù)據(jù)庫(kù)用戶(hù)密碼的方法

    MD5技術(shù)主要用于對(duì)用戶(hù)密碼加密,增加賬戶(hù)的安全性,他具有不可逆的特性,不會(huì)被輕易解密,這篇文章給大家介紹SpringBoot+MyBatis實(shí)現(xiàn)MD5加密數(shù)據(jù)庫(kù)用戶(hù)密碼的方法,感興趣的朋友跟隨小編一起看看吧
    2024-03-03
  • idea創(chuàng)建maven項(xiàng)目速度慢的三種解決方案

    idea創(chuàng)建maven項(xiàng)目速度慢的三種解決方案

    這篇文章主要介紹了idea創(chuàng)建maven項(xiàng)目速度慢的三種解決方案,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • 如何在Spring Boot中實(shí)現(xiàn)異步處理與并發(fā)控制

    如何在Spring Boot中實(shí)現(xiàn)異步處理與并發(fā)控制

    本文我們將深入探討如何在Spring Boot中實(shí)現(xiàn)異步處理與并發(fā)控制,這一過(guò)程涉及到異步任務(wù)的執(zhí)行、線(xiàn)程池的配置、以及并發(fā)控制的實(shí)踐,以幫助我們提升應(yīng)用的性能和響應(yīng)能力,感興趣的朋友跟隨小編一起看看吧
    2024-07-07
  • SpringIOC DI循環(huán)依賴(lài)實(shí)例詳解

    SpringIOC DI循環(huán)依賴(lài)實(shí)例詳解

    這篇文章主要介紹了SpringIOC——DI循環(huán)依賴(lài),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-03-03
  • 淺談spring-boot 允許接口跨域并實(shí)現(xiàn)攔截(CORS)

    淺談spring-boot 允許接口跨域并實(shí)現(xiàn)攔截(CORS)

    本篇文章主要介紹了淺談spring-boot 允許接口跨域并實(shí)現(xiàn)攔截(CORS),具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-08-08

最新評(píng)論