Springboot整合mybatis+JWT

Posted 暴躁的程序猿啊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot整合mybatis+JWT相关的知识,希望对你有一定的参考价值。

Springboot整合mybatis+JWT

本文学习了网络上的视频资源 此处

导入依赖

<!--引入JWT依赖-->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.2</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.19</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

指定数据源信息

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.mapper-locations=classpath:mapper/*.xml

根据数据库的表建立一个pojo

@Data
//开启链式编程
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private String id;
    private String name;
    private String password;
}

创建一个dao

/**
 * @create: 2021/8/27
 * @author: Tony Stark
 */
@Mapper
public interface UserDao {

    /**
     *
     * @param user
     * @return
     */
    User login(User user);

}

在指定路径 resource下的mapper文件夹中编写映射文件

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.rpf.dao.UserDao">
   <select id="login" resultType="com.rpf.pojo.User">
        select * from user where name=#{name} and password=#{password}
    </select>
</mapper>

service

/**
 * @create: 2021/8/27
 * @author: Tony Stark
 */
public interface UserService {
    /**
     * 登录的方法
     * @param user
     * @return
     */
    User login(User user);
}

ServiceImpl

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User login(User user) {

        User login = userDao.login(user);
        if (login!=null){
            return login;
        }
        throw new RuntimeException("登录失败,账号密码错误");
    }
}

UserController

/**
 * @create: 2021/8/27
 * @author: Tony Stark
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @GetMapping("/user/login")
    public Map<String, Object> login(User user) {
        log.info("name : [{}]" + user.getName());
        HashMap<String, Object> map = new HashMap<>(16);
        try {
            User login = userService.login(user);
            HashMap<String, String> payload = new HashMap<>(16);
            payload.put("id", user.getId());
            payload.put("name", user.getName());
            //生成的JWT令牌
            String token = JwtUtils.getToken(payload);
            //响应token
            map.put("token", token);
            map.put("state", true);
            map.put("msg", "登陆成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "登录失败");
        }
        return map;
    }
}

用拦截器验证token解决代码冗余
JWT推荐把token放在请求头中而不是参数中 所以我们应该获取请求头中的token验证;

编写一个拦截器

public class JWTInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("token");
        HashMap<String, Object> map = new HashMap<>(16);
        try {
            //验证token
            JwtUtils.verify(token);
            //放行请求
            return true;
        } catch (SignatureVerificationException e) {
            map.put("msg", "无效签名!");
            e.printStackTrace();
        } catch (TokenExpiredException e) {
            map.put("msg", "token过期!");
            e.printStackTrace();
        } catch (AlgorithmMismatchException e) {
            map.put("mag", "算法不一致!");
            e.printStackTrace();
        } catch (Exception e) {
            map.put("msg", "token无效");
            e.printStackTrace();
        }
        //设置状态
        map.put("state",false);
        //将map转换为json
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
        return false;
    }
}

编写配置类把拦截器注册进去

**
 * @create: 2021/8/28
 * @author: Tony Stark
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JWTInterceptor())
                //拦截路径
                .addPathPatterns("/user/test")
                //放行路径
                .excludePathPatterns("/user/login");
    }
}

创建一个测试的方法

@GetMapping("/user/test")
public Map<String, Object> test(HttpServletRequest request) {
    HashMap<String, Object> map = new HashMap<>(16);
    //获取请求头中的token
    String token = request.getHeader("token");
    //获取token中的信息
    DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
    //获取用户id
    String userId = tokenInfo.getClaim("userId").asString();
    System.out.println(userId);
    map.put("state",true);
        map.put("msg","请求成功!");
    return map;
}

使用postman发送登录请求 生成一个token

http://localhost:8080/user/login?name=飞飞&password=2580

返回结果

{

    "msg": "登陆成功",

    "state": true,

    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi6aOe6aOeIiwiZXhwIjoxNjMwNTQzOTk4fQ.APSlBZaFK3XrgZml4XssayYIf5Oc2dBBQSClsqqCu-A"

}

请求其他方法时我们需要在head头中带上token 不然拦截器会拦截 禁止放行

如果我们的请求头中不带token

返回结果

{
    "msg": "token无效",
    "state": false
}

带上token

{
    "msg": "请求成功!",
    "state": true
}

以上是关于Springboot整合mybatis+JWT的主要内容,如果未能解决你的问题,请参考以下文章

springboot整合jwt

玩转 SpringBoot 2 之整合 JWT 上篇

springboot整合mybatis,redis,代码

SpringBoot整合Mybatis之Annotation

JWT整合Springboot

玩转 SpringBoot 2 之整合 JWT 下篇