「小程序JAVA实战」小程序的springboot后台拦截器(61)

时间:2022-09-05 10:46:12

转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudespringboothoutailanjieqi60/

之前咱们把用户登录,注册成功的信息都放到redis里面了,如果产品经理有一种场景,就是同一个用户在同一个时间以最后一个登录为准,那么前一个就需要重新登录,并且清空前一个用户缓存。这就用到了springboot的缓存机制。源码:https://github.com/limingios/wxProgram.git 中No.15和springboot

拦截器的创建

通过前端传递过来的userToken,和从redis里面获取到的userToken对比,如果不一致,前端传递过来的这个session奖杯提示用户被挤出,直接缓存失效。需要重新登录。

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"; /**
* 拦截请求,在controller调用之前
*/
@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("请登录...");
returnErrorResponse(response, new JSONResult().errorTokenMsg("请登录..."));
return false;
} else {
if (!uniqueToken.equals(userToken)) {
System.out.println("账号被挤出...");
returnErrorResponse(response, new JSONResult().errorTokenMsg("账号被挤出..."));
return false;
}
}
} else {
System.out.println("请登录...");
returnErrorResponse(response, new JSONResult().errorTokenMsg("请登录..."));
return false;
} /**
* 返回 false:请求被拦截,返回
* 返回 true :请求OK,可以继续执行,放行
*/
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();
}
}
} /**
* 请求controller之后,渲染视图之前
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
} /**
* 请求controller之后,视图渲染之后
*/
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
} }

每一个拦截器有需要实现HandlerInterceptor接口,这个接口有三个方法,每个方法会在请求调用的不同时期完成,因为我们需要在接口调用之前拦截请求判断是否登陆,所以这里需要使用preHandle方法,在里面是验证逻辑,最后返回true或者false,确定请求是否合法。

「小程序JAVA实战」小程序的springboot后台拦截器(61)

拦截器加入配置中

原来咱们在spring mvc的时候都是通过xml配置文件的方法,springboot为了简化,都是通过java来进行配置,刚创建的拦截器需要配置在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; @Configuration
public 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实战」小程序的springboot后台拦截器(61)

小程序针对返回的502问题添加判断

在通过userId获取用户的信息时,在header中添加用户的userId,userToken,针对登录后返回502进行提示并清空用户信息缓存。

“` javascript
// pages/mine/mine.js
const app = getApp()
var videoUtils = require(‘../../utils/videoUtils.js’)
Page({

/**
* 页面的初始数据
*/
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’ // 默认值
},
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, // 默认9
sizeType: [‘compressed’], // 可以指定是原图还是压缩图,默认二者都有
sourceType: [‘album’, ‘camera’], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths
if (tempFilePaths.length > 0) {
console.log(tempFilePaths[0]);
wx.uploadFile({
url: app.serverUrl + “/user/uploadFace?userId=” + user.id, //仅为示例,非真实的接口地址
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
})
}
}
})
} }
})

},
/**
* 生命周期函数–监听页面加载
*/
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’, // 默认值
‘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();
},

/**
* 生命周期函数–监听页面初次渲染完成
*/
onReady: function() {

},

/**
* 生命周期函数–监听页面显示
*/
onShow: function() {

},

/**
* 生命周期函数–监听页面隐藏
*/
onHide: function() {

},

/**
* 生命周期函数–监听页面卸载
*/
onUnload: function() {

},

/**
* 页面相关事件处理函数–监听用户下拉动作
*/
onPullDownRefresh: function() {

},

/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function() {

},

/**
* 用户点击右上角分享
*/
onShareAppMessage: function() {

}
})
““

「小程序JAVA实战」小程序的springboot后台拦截器(61)

PS:通过拦截器的方式很好的保护后台的程序正常的运行。

「小程序JAVA实战」小程序的springboot后台拦截器(61)的更多相关文章

  1. 「小程序JAVA实战」小程序的页面重定向(60)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeyemianzhongdingxiang59/ 在我们正常的浏览网 ...

  2. 「小程序JAVA实战」小程序的留言和评价功能(70)

    转自:https://idig8.com/2018/10/28/xiaochengxujavashizhanxiaochengxudeliuyanhepingjiagongneng69/ 目前小程序这 ...

  3. 「小程序JAVA实战」小程序的视频点赞功能开发(62)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeshipindianzangongnengkaifa61/ 视频点 ...

  4. 「小程序JAVA实战」小程序的flex布局(22)

    转自:https://idig8.com/2018/08/09/xiaochengxu-chuji-22/ 之前已经把小程序的框架说完了,接下来说说小程序的组件,在说组件之前,先说说布局吧.源码:ht ...

  5. 「小程序JAVA实战」小程序的视频展示页面初始化(63)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeshipinzhanshiyemianchushihua62/ 进 ...

  6. 「小程序JAVA实战」小程序开发注册用户的接口(33)

    转自:https://idig8.com/2018/08/30/xiaochengxujavashizhanxiaochengxukaifazhuceyonghudejiekou33/ 从用户注册接口 ...

  7. 「小程序JAVA实战」小程序的举报功能开发(68)

    转自:https://idig8.com/2018/09/25/xiaochengxujavashizhanxiaochengxudeweixinapicaidancaozuo66-2/ 通过点击举报 ...

  8. 「小程序JAVA实战」小程序的个人信息作品,收藏,关注(66)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudegerenxinxizuopinshoucangguanzhu65 ...

  9. 「小程序JAVA实战」小程序的关注功能(65)

    转自:https://idig8.com/2018/09/24/xiaochengxujavashizhanxiaochengxudeguanzhugongneng64/ 在个人页面,根据发布者个人和 ...

随机推荐

  1. Swift - 获取、改变按钮的标题文本(UIButton点击切换title)

    在开发中,我们常常需要动态地改变按钮标签文字,使用 setTitle() 函数就可以了.有时我们需要在几个标题间切换,比如下面样例所示,按钮点击后按钮文字会在"播放""暂 ...

  2. Struts表单格局;theme三个属性值:simple,xhtml,css_xhtml

    转自:http://www.educity.cn/wenda/7156.html 解决Struts2 Form表单自己布局之前先看看 theme 属性, theme属性提供 三个属性值:simple, ...

  3. form 提交

    1.方式1:字段加验证 @model MvcWeb.Models.UserInfo @{ ViewBag.Title = "Add"; } <h2>Add</h2 ...

  4. css js 优化工具

    我知道国内很多网页制作人员都还在制作table式网页,这样的网页打开速度很慢.如果要想网站打开速度快,就要学会使用DIV+CSS,将图片写进CSS,这样如果网站内容很多的时候,也不会影响网页的浏览.它 ...

  5. linux tcp中time&lowbar;wait

    http://www.cnblogs.com/my_life/articles/3460873.html http://blog.csdn.net/sunnydogzhou/article/detai ...

  6. JavaScript 版本的 RSA加密库文件

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...

  7. glance系列二:glance部署及操作

    一 简单架构图示参考 更新中... 二 部署glance yum install memcached python-memcachedsystemctl enable memcached.servic ...

  8. 你应该知道的JAVA面试题

    你应该知道的JAVA面试题 经常面试一些候选人,整理了下我面试使用的题目,陆陆续续整理出来的题目很多,所以每次会抽一部分来问.答案会在后面的文章中逐渐发布出来. 基础题目 Java线程的状态 进程和线 ...

  9. 查找mysql的cnf文件位置

    mysql --help|grep 'my.cnf' 查看mysql启动时读取配置文件的默认目录 命令 mysql --help|grep 'my.cnf' 输出 order of preferenc ...

  10. python 文件&lpar;file&rpar;操作

    操作文件的一般流程有: 打开文件.文件处理.关闭文件 开开文件的模式有: r,只读模式(默认). w,只写模式.[不可读:不存在则创建:存在则删除内容:] a,追加模式.[不可读: 不存在则创建:存在 ...