1、数据库
就是一个表,三个字段
创建一个springboot项目,省略了。。。。
2、导入依赖包
mysql,lombok,mybatis-plus,jwt
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
3、数据库配置文件
#数据库连接配置
spring.datasource.username=root
spring.datasource.password=123456
#mysql5~8 驱动不同driver-class-name 8需要增加时区的配置serverTimezone=UTC
#useSSL=false 安全连接
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus_study_one?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4、封装JWT工具类
public class JWTUtils {
private static String SECRET = "token!Q@W#E$R";
/**
* 生产token
*/
public static String getToken(Map<String, String> map) {
JWTCreator.Builder builder = JWT.create();
//payload
map.forEach((k, v) -> {
builder.withClaim(k, v);
});
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE, 7); //默认7天过期
builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
String token = builder.sign(Algorithm.HMAC256(SECRET));//签名
return token;
}
/**
* 验证token
*/
public static DecodedJWT verify(String token) {
//如果有任何验证异常,此处都会抛出异常
DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
return decodedJWT;
}
}
5、实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Admin {
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
private String password;
}
6、service
public interface AdminService extends IService<Admin> {
/**
* 登录接口
*
* @param admin 表单中的user
* @return 数据库中查询到的User
*/
Admin login(Admin admin);
}
7、servicelmpl
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
@Autowired
private AdminMapper adminMapper;
@Override
public Admin login(Admin admin) {
QueryWrapper<Admin> wrapper = new QueryWrapper<>();
wrapper.eq("name",admin.getName());
wrapper.eq("password",admin.getPassword());
System.out.println(admin.getName());
System.out.println(admin.getPassword());
//若出现多个结果使用list或map
Admin adminDB = adminMapper.selectOne(wrapper); //查询一个数据,若出现多个结果使用list或map
if (adminDB != null) {
return adminDB;
}
throw new RuntimeException("认证失败");
}
}
8、mapper
@Repository
public interface AdminMapper extends BaseMapper<Admin> {
}
完成的目录结构如下: