SpringBoot日记本系统全程直播03:把登录后台接起来撒~~(二)

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: SpringBoot日记本系统全程直播03:把登录后台接起来撒~~

4. sa-token 鉴权框架


用户权限问题是一个系统不可缺少的部分,本项目采用sa-token框架。倒不是我给作者打广告哈,而是我觉得确实很好用,shiro太重了,我更倾向于选择sa-token,用我们国人自己的框架。

官网:Sa-Token

引入依赖:

<!-- Sa-Token 权限认证-->
<dependency>
  <groupId>cn.dev33</groupId>
  <artifactId>sa-token-spring-boot-starter</artifactId>
  <version>1.28.0</version>
</dependency>


创建包


com.rabbit.diary.config

编写


SaTokenConfigure

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    // 注册Sa-Token的注解拦截器,打开注解式鉴权功能
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册注解拦截器,并排除不需要注解鉴权的接口地址 (与登录拦截器无关)
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
    }
}

写这个config是为了开启sa-token注解。


5. 用户接口和服务类

终于到用户接口编写啦,我们已经做了很多的准备工作,这个项目已经初步具备企业级工程化的标准了。很多企业小项目的架构杂乱无章,甚至都没有这么完备的体系。


用户服务类,我们采用接口+实现类的方式。


1.png


UserService

package com.rabbit.diary.service;
import com.rabbit.diary.bean.User;
import org.springframework.stereotype.Service;
public interface UserService {
    User getByUserName(String userName);
    void save(User user);
}


UserServiceImpl

package com.rabbit.diary.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbit.diary.bean.User;
import com.rabbit.diary.dao.UserMapper;
import com.rabbit.diary.redis.RedisServiceImpl;
import com.rabbit.diary.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.annotation.Annotation;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisServiceImpl redisServiceImpl;
    /**
     * 根据用户名获取用户
     * @param userName
     * @return
     */
    @Override
    public User getByUserName(String userName) {
        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("user_name", userName));
        if(users.size() > 0){
            return users.get(0);
        }
        return null;
    }
    /**
     * 保存用户
     * @param user
     */
    @Override
    public void save(User user) {
        userMapper.insert(user);
    }
}


很简单吧,就两个方法。

UserController:


1.png


package com.rabbit.diary.web;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.rabbit.diary.bean.User;
import com.rabbit.diary.bean.core.BizException;
import com.rabbit.diary.bean.core.ExceptionCodeEnum;
import com.rabbit.diary.bean.core.Result;
import com.rabbit.diary.redis.RedisServiceImpl;
import com.rabbit.diary.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisServiceImpl redisServiceImpl;
    String salt = "diary188";
    @RequestMapping("register")
    public Result register(@RequestBody User user){
        if(StrUtil.isEmpty(user.getUserName())){
            throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("用户名不允许为空!"));
        }
        if(StrUtil.isEmpty(user.getPassword())){
            throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("密码不允许为空!"));
        }
        //检查用户名是否重复
        if(userService.getByUserName(user.getUserName()) != null){
            throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("用户名"+user.getUserName()+"重复!"));
        }
        //拼装userBean
        user.setUid(redisServiceImpl.getIncr("userId")); //redis自增ID
        user.setPassword(SecureUtil.md5(user.getPassword() + salt));
        user.setCreateTime(DateUtil.now());
        user.setUpdateTime(DateUtil.now());
        userService.save(user);
        return Result.success();
    }
    @RequestMapping("login")
    public Result login(@RequestBody User user){
        User user1 = userService.getByUserName(user.getUserName());
        if(user1 == null){
            throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("不存在的用户名:" + user.getUserName()));
        }
        String password = SecureUtil.md5(user.getPassword() + salt);
        if(!user1.getPassword().equals(password)){
            throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("账号和密码不匹配:" + user.getUserName()));
        }
        /**登录维持ID* */
        StpUtil.login(user1.getUid(),"PC");
        return Result.success();
    }
}


下面我们挑几个需要注意的点

01. 如何实现redis自增长ID?

 user.setUid(redisServiceImpl.getIncr("userId")); //redis自增ID

02.如何保持登录ID?

StpUtil.login(user1.getUid(),"PC");


PageController

@Controller
public class PageController {
    @RequestMapping("login")
    public String login(){
        return "login";
    }
    @RequestMapping("/")
    @SaCheckLogin
    public String index(){
        return "index";
    }
}


注意,我们给index加上了saCheckLogin注解,这表示进入这个方法必须得是登录状态。

index.jsp是项目首页


1.png


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<c:set var="basePath" value="${pageContext.request.contextPath}"></c:set>
<html>
<head>
    <title>Title</title>
    <script src="${basePath}/layui/layui.all.js" charset="utf-8"></script>
    <link rel="stylesheet" href="${basePath}/layui/css/layui.css" media="all">
</head>
<body>
    首页
</body>
</html>


启动项目,让我们访问:http://localhost/


看到:


{"code":"9999","message":"Token无效:3fd99f78-10aa-4690-bd83-5fae198d1b87","data":null}

这表示sa-token的配置已经生效了。


现在,我们去注册几个账号:


9.png


10.png


11.png


这就顺利进入了index.jsp。


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
2天前
|
前端开发 Java 关系型数据库
Java医院绩效考核系统源码B/S架构+springboot三级公立医院绩效考核系统源码 医院综合绩效核算系统源码
作为医院用综合绩效核算系统,系统需要和his系统进行对接,按照设定周期,从his系统获取医院科室和医生、护士、其他人员工作量,对没有录入信息化系统的工作量,绩效考核系统设有手工录入功能(可以批量导入),对获取的数据系统按照设定的公式进行汇算,且设置审核机制,可以退回修正,系统功能强大,完全模拟医院实际绩效核算过程,且每步核算都可以进行调整和参数设置,能适应医院多种绩效核算方式。
20 2
|
2天前
|
运维 监控 Java
springboot基层区域HIS系统源码
医疗(医院)机构正式使用云HIS系统之前,要先进行院内基础数据的配置,主要在数据管理模块中进行,由系统管理员来操作。
9 0
|
4天前
|
传感器 人工智能 前端开发
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
智慧校园电子班牌,坐落于班级的门口,适合于各类型学校的场景应用,班级学校日常内容更新可由班级自行管理,也可由学校统一管理。让我们一起看看,电子班牌有哪些功能呢?
45 4
JAVA语言VUE2+Spring boot+MySQL开发的智慧校园系统源码(电子班牌可人脸识别)Saas 模式
|
22天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的4S店客户管理系统的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的4S店客户管理系统的详细设计和实现
43 4
|
22天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的汽车保养系统的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的汽车保养系统的详细设计和实现
10 1
|
22天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的个人行政复议在线预约系统的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的个人行政复议在线预约系统的详细设计和实现
28 1
|
22天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的医院核酸检测服务系统的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的医院核酸检测服务系统的详细设计和实现
39 0
|
1月前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
1月前
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
97 2
|
1月前
|
前端开发 JavaScript Java
6个SpringBoot 项目拿来就可以学习项目经验接私活
6个SpringBoot 项目拿来就可以学习项目经验接私活
40 0