溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

「小程序JAVA實(shí)戰(zhàn)」小程序的springboot后臺(tái)攔截器

發(fā)布時(shí)間:2020-07-07 16:58:24 來源:網(wǎng)絡(luò) 閱讀:249 作者:IT人故事 欄目:移動(dòng)開發(fā)

之前咱們把用戶登錄,注冊(cè)成功的信息都放到redis里面了,如果產(chǎn)品經(jīng)理有一種場(chǎng)景,就是同一個(gè)用戶在同一個(gè)時(shí)間以最后一個(gè)登錄為準(zhǔn),那么前一個(gè)就需要重新登錄,并且清空前一個(gè)用戶緩存。這就用到了springboot的緩存機(jī)制。源碼:https://github.com/limingios/wxProgram.git?中No.15和springboot

攔截器的創(chuàng)建

通過前端傳遞過來的userToken,和從redis里面獲取到的userToken對(duì)比,如果不一致,前端傳遞過來的這個(gè)session獎(jiǎng)杯提示用戶被擠出,直接緩存失效。需要重新登錄。

package?com.idig8.controller.interceptor;import?java.io.IOException;import?java.io.OutputStream;import?java.io.UnsupportedEncodingException;import?javax.servlet.http.HttpServletRequest;import?javax.servlet.http.HttpServletResponse;import?org.apache.commons.lang3.StringUtils;import?org.springframework.beans.factory.annotation.Autowired;import?org.springframework.web.servlet.HandlerInterceptor;import?org.springframework.web.servlet.ModelAndView;import?com.idig8.utils.JSONResult;import?com.idig8.utils.JsonUtils;import?com.idig8.utils.RedisOperator;public?class?MiniInterceptor?implements?HandlerInterceptor?{????@Autowired
????public?RedisOperator?redis;????public?static?final?String?USER_REDIS_SESSION?=?"user-redis-session";????
????/**
?????*?攔截請(qǐng)求,在controller調(diào)用之前
?????*/
????@Override
????public?boolean?preHandle(HttpServletRequest?request,?HttpServletResponse?response,?
????????????Object?arg2)?throws?Exception?{
????????String?userId?=?request.getHeader("headerUserId");
????????String?userToken?=?request.getHeader("headerUserToken");????????
????????if?(StringUtils.isNotBlank(userId)?&&?StringUtils.isNotBlank(userToken))?{
????????????String?uniqueToken?=?redis.get(USER_REDIS_SESSION?+?":"?+?userId);????????????if?(StringUtils.isEmpty(uniqueToken)?&&?StringUtils.isBlank(uniqueToken))?{
????????????????System.out.println("請(qǐng)登錄...");
????????????????returnErrorResponse(response,?new?JSONResult().errorTokenMsg("請(qǐng)登錄..."));????????????????return?false;
????????????}?else?{????????????????if?(!uniqueToken.equals(userToken))?{
????????????????????System.out.println("賬號(hào)被擠出...");
????????????????????returnErrorResponse(response,?new?JSONResult().errorTokenMsg("賬號(hào)被擠出..."));????????????????????return?false;
????????????????}
????????????}
????????}?else?{
????????????System.out.println("請(qǐng)登錄...");
????????????returnErrorResponse(response,?new?JSONResult().errorTokenMsg("請(qǐng)登錄..."));????????????return?false;
????????}????????
????????
????????/**
?????????*?返回?false:請(qǐng)求被攔截,返回
?????????*?返回?true?:請(qǐng)求OK,可以繼續(xù)執(zhí)行,放行
?????????*/
????????return?true;
????}????
????public?void?returnErrorResponse(HttpServletResponse?response,?JSONResult?result)?
????????????throws?IOException,?UnsupportedEncodingException?{
????????OutputStream?out=null;????????try{
????????????response.setCharacterEncoding("utf-8");
????????????response.setContentType("text/json");
????????????out?=?response.getOutputStream();
????????????out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
????????????out.flush();
????????}?finally{????????????if(out!=null){
????????????????out.close();
????????????}
????????}
????}????
????/**
?????*?請(qǐng)求controller之后,渲染視圖之前
?????*/
????@Override
????public?void?postHandle(HttpServletRequest?arg0,?HttpServletResponse?arg1,?Object?arg2,?ModelAndView?arg3)
????????????throws?Exception?{
????}????
????/**
?????*?請(qǐng)求controller之后,視圖渲染之后
?????*/
????@Override
????public?void?afterCompletion(HttpServletRequest?arg0,?HttpServletResponse?arg1,?Object?arg2,?Exception?arg3)
????????????throws?Exception?{
????}

}

每一個(gè)攔截器有需要實(shí)現(xiàn)HandlerInterceptor接口,這個(gè)接口有三個(gè)方法,每個(gè)方法會(huì)在請(qǐng)求調(diào)用的不同時(shí)期完成,因?yàn)槲覀冃枰诮涌谡{(diào)用之前攔截請(qǐng)求判斷是否登陸,所以這里需要使用preHandle方法,在里面是驗(yàn)證邏輯,最后返回true或者false,確定請(qǐng)求是否合法。

「小程序JAVA實(shí)戰(zhàn)」小程序的springboot后臺(tái)攔截器

攔截器加入配置中

原來咱們?cè)趕pring mvc的時(shí)候都是通過xml配置文件的方法,springboot為了簡(jiǎn)化,都是通過java來進(jìn)行配置,剛創(chuàng)建的攔截器需要配置在webconfig里面

package?com.idig8;import?org.springframework.beans.factory.annotation.Value;import?org.springframework.context.annotation.Bean;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.WebMvcConfigurerAdapter;import?com.idig8.controller.interceptor.MiniInterceptor;@Configurationpublic?class?WebMvcConfig?extends?WebMvcConfigurerAdapter?{????
????@Value("${server.file.path}")????private?String?fileSpace;????@Override
????public?void?addResourceHandlers(ResourceHandlerRegistry?registry)?{????????//資源的路徑.swagger2的資源.所在的目錄,
????????registry.addResourceHandler("/**")
????????.addResourceLocations("classpath:/META-INF/resources/")
????????.addResourceLocations("file:"+fileSpace);
????????
????}????
????@Bean
????public?MiniInterceptor?miniInterceptor()?{????????return?new?MiniInterceptor();
????}????@Override
????public?void?addInterceptors(InterceptorRegistry?registry)?{
????????
????????registry.addInterceptor(miniInterceptor()).addPathPatterns("/user/**")
???????????????????????.addPathPatterns("/video/upload",?"/video/uploadCover")
??????????????????????????????????????????????????.addPathPatterns("/bgm/**");????????
????????super.addInterceptors(registry);
????}

}

「小程序JAVA實(shí)戰(zhàn)」小程序的springboot后臺(tái)攔截器

小程序針對(duì)返回的502問題添加判斷

在通過userId獲取用戶的信息時(shí),在header中添加用戶的userId,userToken,針對(duì)登錄后返回502進(jìn)行提示并清空用戶信息緩存。

//?pages/mine/mine.jsconst?app?=?getApp()var?videoUtils?=?require('../../utils/videoUtils.js')
Page({??/**
???*?頁(yè)面的初始數(shù)據(jù)
???*/
??data:?{????faceImage:?"../../resource/images/noneface.png",????nickname:?"昵稱",????fansCounts:?0,????followCounts:?0,????receiveLikeCounts:?0,
??},??/**
???*?用戶注銷
???*/
??logout:?function(e)?{????var?user?=?app.getGlobalUserInfo();
????wx.showLoading({??????title:?'正在注銷中。。。'
????});
????wx.request({??????url:?app.serverUrl?+?"/logout?userId="?+?user.id,??????method:?"POST",??????header:?{????????'content-type':?'application/json'?//?默認(rèn)值
??????},??????success:?function(res)?{????????console.log(res.data);????????var?status?=?res.data.status;
????????wx.hideLoading();????????if?(status?==?200)?{
??????????wx.showToast({????????????title:?"用戶注銷成功~!",????????????icon:?'none',????????????duration:?3000
??????????})??????????//?app.userInfo?=?null;
??????????wx.removeStorageSync("userInfo");
??????????wx.redirectTo({????????????url:?'../userRegister/userRegister',
??????????})

????????}?else?if?(status?==?500)?{
??????????wx.showToast({????????????title:?res.data.msg,????????????icon:?'none',????????????duration:?3000
??????????})
????????}
??????}
????})
??},??/**
???*?頭像上傳
???*/
??uploadFace:?function(e)?{????//?var?user?=?app.userInfo;
????var?user?=?app.getGlobalUserInfo();????var?me?=?this;
????wx.chooseImage({??????count:?1,?//?默認(rèn)9
??????sizeType:?['compressed'],?//?可以指定是原圖還是壓縮圖,默認(rèn)二者都有
??????sourceType:?['album',?'camera'],?//?可以指定來源是相冊(cè)還是相機(jī),默認(rèn)二者都有
??????success:?function(res)?{????????//?返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片
????????var?tempFilePaths?=?res.tempFilePaths????????if?(tempFilePaths.length?>?0)?{??????????console.log(tempFilePaths[0]);
??????????wx.uploadFile({????????????url:?app.serverUrl?+?"/user/uploadFace?userId="?+?user.id,?//僅為示例,非真實(shí)的接口地址
????????????filePath:?tempFilePaths[0],????????????name:?'file',????????????success:?function(res)?{??????????????var?data?=?JSON.parse(res.data);??????????????console.log(data);
??????????????wx.hideLoading();??????????????if?(data.status?==?200)?{
????????????????wx.showToast({??????????????????title:?"用戶上傳成功~!",??????????????????icon:?'none',??????????????????duration:?3000
????????????????})
????????????????me.setData({??????????????????faceUrl:?app.serverUrl?+?data.data
????????????????})


??????????????}?else?if?(data.status?==?500)?{
????????????????wx.showToast({??????????????????title:?data.msg,??????????????????icon:?'none',??????????????????duration:?3000
????????????????})
??????????????}
????????????}
??????????})
????????}

??????}
????})
??},??/**
???*?生命周期函數(shù)--監(jiān)聽頁(yè)面加載
???*/
??onLoad:?function(options)?{????var?me?=?this;????var?userInfo?=?app.getGlobalUserInfo();
????wx.showLoading({??????title:?'正在獲取用戶信息。。。'
????});
????wx.request({??????url:?app.serverUrl?+?"/user/queryByUserId?userId="?+?userInfo.id,??????method:?"POST",??????header:?{????????'content-type':?'application/json',?//?默認(rèn)值
????????'headerUserId':?userInfo.id,????????'headerUserToken':?userInfo.userToken
??????},??????success:?function(res)?{????????console.log(res.data);????????var?status?=?res.data.status;????????if?(status?==?200)?{??????????var?userInfo?=?res.data.data;
??????????wx.hideLoading();??????????var?faceImage?=?me.data.faceUrl;??????????if?(userInfo.faceImage?!=?null?&&?userInfo.faceImage?!=?''?&&?userInfo.faceImage?!=?undefined)?{
????????????faceImage?=?app.serverUrl?+?userInfo.faceImage;
??????????}
??????????me.setData({????????????faceImage:?faceImage,????????????fansCounts:?userInfo.fansCounts,????????????followCounts:?userInfo.followCounts,????????????receiveLikeCounts:?userInfo.receiveLikeCounts,????????????nickname:?userInfo.nickname
??????????})
????????}?else?if?(status?==?502){
??????????wx.showToast({????????????title:?res.data.msg,????????????duration:3000,????????????icon:'none',????????????complete:function(){
??????????????wx.removeStorageSync("userInfo");

??????????????wx.navigateTo({????????????????url:?'../userLogin/userLogin',
??????????????})
????????????}
??????????})
??????????
????????}
??????}
????})
??},??uploadVideo:?function(e)?{
????videoUtils.uploadVideo();
??},??/**
???*?生命周期函數(shù)--監(jiān)聽頁(yè)面初次渲染完成
???*/
??onReady:?function()?{

??},??/**
???*?生命周期函數(shù)--監(jiān)聽頁(yè)面顯示
???*/
??onShow:?function()?{

??},??/**
???*?生命周期函數(shù)--監(jiān)聽頁(yè)面隱藏
???*/
??onHide:?function()?{

??},??/**
???*?生命周期函數(shù)--監(jiān)聽頁(yè)面卸載
???*/
??onUnload:?function()?{

??},??/**
???*?頁(yè)面相關(guān)事件處理函數(shù)--監(jiān)聽用戶下拉動(dòng)作
???*/
??onPullDownRefresh:?function()?{

??},??/**
???*?頁(yè)面上拉觸底事件的處理函數(shù)
???*/
??onReachBottom:?function()?{

??},??/**
???*?用戶點(diǎn)擊右上角分享
???*/
??onShareAppMessage:?function()?{

??}
})

「小程序JAVA實(shí)戰(zhàn)」小程序的springboot后臺(tái)攔截器

PS:通過攔截器的方式很好的保護(hù)后臺(tái)的程序正常的運(yùn)行。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI