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

SpringBoot統(tǒng)一功能處理示例詳解(攔截器)

 更新時(shí)間:2023年08月05日 16:09:59   作者:白楊783  
這篇文章主要介紹了SpringBoot統(tǒng)一功能處理(攔截器),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

1.用戶登錄權(quán)限校驗(yàn)

1.1自定義攔截器

寫一個(gè)類去實(shí)現(xiàn)HandlerInterceptor接口表示當(dāng)前類是一個(gè)攔截器,再重寫HandlerInterceptor接口中的方法,preHandle為在方法執(zhí)行前攔截,postHandle為方法執(zhí)行中攔截,afterCompletion為方法執(zhí)行中攔截.需要在什么時(shí)候攔截就重寫什么方法

@Component
public class LoginIntercepetor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判斷用戶登錄
        HttpSession session = request.getSession(false);
        if(session!=null && session.getAttribute(ApplicationVariable.SESSION_USERINFO_KEY)!=null){
            // 用戶已經(jīng)登錄
            return true;
        }
        // 當(dāng)代碼執(zhí)行到此處說(shuō)明用戶未登錄
        response.sendRedirect("/login.html");
        return false;
    }
}

1.2.配置攔截規(guī)則

@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**") //攔截所有的URL
                .excludePathPatterns("/user/login") // 排除 url /user/login 不攔截
                .excludePathPatterns("/user/reg") // 排除 url /user/login 不攔截
        ;
    }
}

實(shí)現(xiàn)WebMvcConfigurer接口,重寫WebMvcConfigurer中的addInterceptors方法,在使用 InterceptorRegistry參數(shù) 配置攔截規(guī)則

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

統(tǒng)一異常處理

創(chuàng)建異常處理類

@ControllerAdvice
@ResponseBody
public class MyExceptionAdvice {
}

ControllerAdvice注解的作用:1.和Controller注解作用一樣,讓這個(gè)類隨著Spring的啟動(dòng)而啟動(dòng). 2.監(jiān)測(cè)添加了Controller注解的類的異常 

創(chuàng)建異常檢測(cè)的類和處理業(yè)務(wù)

@ExceptionHandler(NullPointerException.class)
public HashMap<String,Object> dpNullPointerException(NullPointerException e){
        HashMap<String,Object> result = new HashMap<>();
        result.put("code",-1);
        result.put("msg","空指針: "+e.getMessage());
        result.put("data",null);
        return result;
        }

使用@ExceptionHandler注解,括號(hào)里面寫要捕獲的異常,用HashMap的方式返回?cái)?shù)據(jù)給前端,此處以捕獲空指針異常為例,如果想要捕獲所有的異常,可以使用所有異常的父類Exception

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

統(tǒng)一數(shù)據(jù)格式返回(在返回?cái)?shù)據(jù)之前進(jìn)行數(shù)據(jù)重寫)

@ControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    ObjectMapper objectMapper;
    /**
     * 是否執(zhí)行 beforeBodyWrite 方法,true=執(zhí)行 重寫返回結(jié)果,false=不執(zhí)行
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }
    /**
     * 在返回?cái)?shù)據(jù)之前進(jìn)行數(shù)據(jù)重寫
     *
     * @param body     原始返回值
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //定義一個(gè)標(biāo)準(zhǔn)的返回格式
        //Hash<String,Object> code,msg,data
        if(body instanceof HashMap){
            return body;
        }
        // 重寫返回結(jié)果,讓其返回一個(gè)統(tǒng)一的數(shù)據(jù)格式
        HashMap<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("msg","");
        result.put("data",body);
        if(body instanceof String){
            // 返回一個(gè) String 字符串
            try {
                objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return result;
        }
        return result;
    }
}

使用ResponseBodyAdvice接口,重寫supports和beforeBodyWrite方法,這種方式如果原方法返回的是字符串,不進(jìn)行特殊處理會(huì)報(bào)錯(cuò)(執(zhí)行流程:

1.方法返回的是 String

2.統(tǒng)一數(shù)據(jù)返回之前處理 把String 轉(zhuǎn)換成 HashMap

3.將 HashMap 轉(zhuǎn)換成 application/json 字符串給前端(接口)),在第三步的時(shí)候會(huì)判斷原 body 類型,根據(jù)類型選擇不同的 消息轉(zhuǎn)換器 去轉(zhuǎn)換,如果是String 類型會(huì)使用StringHttpMessageConverter進(jìn)行類型轉(zhuǎn)換,如果非String 類型,會(huì)使用 HttpMessageConverter 進(jìn)行類型轉(zhuǎn)換.但是事實(shí)上StringHttpMessageConverter 消息轉(zhuǎn)換器不能把HashMap轉(zhuǎn)換為json格式的字符串,因此會(huì)報(bào)錯(cuò).   我們可以在統(tǒng)一數(shù)據(jù)重寫時(shí),單獨(dú)處理String類型,讓其返回一個(gè) String 字符串,而非HashMap

到此這篇關(guān)于SpringBoot統(tǒng)一功能處理(攔截器)的文章就介紹到這了,更多相關(guān)SpringBoot統(tǒng)一功能處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論