【備戰(zhàn)春招】第15天 掃碼登錄 前端
標(biāo)簽:
SpringBoot
课程名称:在线办公系统
课程章节: 第1章
课程讲师:神思者
课程内容
在前端页面 设置一个切换 按钮
<div class="row"><a class="link" @click="changeMode">二维码登陆</a></div>
定义changeMode()函数用来切换登陆面板,其实就是改变qrCodeVisible变量的值。
changeMode: function() {
let that = this;
that.qrCodeVisible = !that.qrCodeVisible;
//加载二维码图片
if (that.qrCodeVisible) {
that.loadQRCode();
//创建刷新二维码定时器,默认为5分钟
that.qrCodeTimer = setInterval(function() {
that.loadQRCode();
}, 5 * 60 * 1000);
//创建轮询定时器,每隔5秒钟发起Ajax请求,检查Redis中UUID对应的值
that.loginTimer = setInterval(function() {
//调用Web方法,检查Redis中UUID对应的值,判定用户是否扫码登陆。该Web方法下面有定义。
that.$http('user/wechatLogin', 'POST', { uuid: that.uuid }, true, function(resp) {
if (resp.result) {
//判定登陆成功就自动销毁两个定时器
clearInterval(that.qrCodeTimer);
clearInterval(that.loginTimer);
//缓存用户权限
let permissions = resp.permissions;
localStorage.setItem('permissions', permissions);
//跳转页面
router.push({ name: 'Home' });
}
});
}, 5000);
} else {
//切换回账户密码登陆,销毁刷新二维码定时器
clearInterval(that.qrCodeTimer);
clearInterval(that.loginTimer);
}},//加载二维码图片的封装方法loadQRCode: function() {
this.$http('user/createQrCode', 'GET', null, true, resp => {
this.qrCode = resp.pic;
this.uuid = resp.uuid;
});}在UserService.java接口中声明抽象方法。
public interface UserService {
……
public HashMap wechatLogin(String uuid);
}在UserServiceImpl.java类中实现抽象方法。
@Servicepublic class UserServiceImpl implements UserService {
@Override
public HashMap wechatLogin(String uuid) {
HashMap map = new HashMap();
boolean result = false;
if (redisTemplate.hasKey(uuid)) {
String value = redisTemplate.opsForValue().get(uuid).toString();
//判断Redis缓存的UUID对应的Value是否为非false,就算用户登陆了
if (!"false".equals(value)) {
result = true;
//删除Redis中的UUID,防止二维码被重刷
redisTemplate.delete(uuid);
//把Value的字符串转换成整数
int userId = Integer.parseInt(value);
map.put("userId", userId);
}
}
map.put("result", result);
return map;
}}创建WechatLoginForm.java类,封装浏览器提交的Ajax数据。
@Schema(name = "WechatLoginForm", description = "微信小程序登陆Emos系统Form类")
@Data
public class WechatLoginForm {
@Schema(description = "uuid")
@NotBlank(message = "uuid不能为空")
private String uuid;
}在UserController.java类中定义Web方法,可以用Swagger测试一下。
@RestController
@RequestMapping("/user")
@Tag(name = "UserController", description = "用户Web接口")public class UserController {
@PostMapping("/wechatLogin")
@Operation(summary = "微信小程序登陆")
public R wechatLogin(@Valid @RequestBody WechatLoginForm form) {
HashMap map = userService.wechatLogin(form.getUuid());
boolean result = (boolean) map.get("result");
if (result) {
int userId = (int) map.get("userId");
StpUtil.setLoginId(userId);
Set<String> permissions = userService.searchUserPermissions(userId);
map.remove("userId");
map.put("permissions", permissions);
String token=StpUtil.getTokenInfo().getTokenValue();
map.put("token",token);
}
return R.ok(map);
}}點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦


