springboot mybatis-plus 登录接口

本文介绍了如何使用SpringBoot和MyBatis-Plus构建一个简单的登录接口,包括添加依赖、创建数据库表和实体类、编写Mapper接口和配置文件,以及在Controller中实现登录逻辑并进行测试。

下面是使用SpringBoot和MyBatis-Plus实现登录接口的示例代码:

  1. 添加依赖

在pom.xml文件中添加以下依赖:

<dependencies>
    <!-- SpringBoot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Mybatis Plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.0</version>
    </dependency>

    <!-- 数据库驱动 -->
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.199</version>
    </dependency>

    <!-- 其他依赖... -->
</dependencies>
  1. 创建数据库表

创建一个名为user的数据库表,包含以下字段:

字段名类型描述
idBIGINT用户ID
nameVARCHAR用户名
pwdVARCHAR用户密码
  1. 创建实体类

创建一个名为User的实体类,映射数据库表user

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id;
    private String name;
    private String pwd;
}
  1. 创建Mapper接口

创建一个名为UserMapper的Mapper接口,使用MyBatis-Plus提供的BaseMapper进行CRUD操作:

public interface UserMapper extends BaseMapper<User> {
}
  1. 编写配置文件

application.properties文件中配置数据库信息:

spring.datasource.url=jdbc:h2:mem:test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

mybatis-plus.mapper-locations=classpath*:mapper/**/*.xml
mybatis-plus.type-aliases-package=com.example.demo.entity
mybatis-plus.configuration.map-underscore-to-camel-case=true
  1. 编写登录接口

创建一个名为UserController的控制器,在其中编写登录接口:

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public String login(@RequestBody User user) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name", user.getName()).eq("pwd", user.getPwd());
        User dbUser = userMapper.selectOne(wrapper);
        if (dbUser != null) {
            return "登录成功";
        } else {
            return "登录失败,用户名或密码错误";
        }
    }
}

该接口使用POST方式请求,接收一个User类型的参数user,其中包含用户名和密码。接口通过使用MyBatis-Plus提供的QueryWrapper查询用户信息,如果查询到了数据,则返回登录成功,否则返回登录失败。

  1. 测试登录接口

启动应用程序,在浏览器中访问http://localhost:8080/login,进行登录测试。例如,以下是使用cURL工具进行登录测试的示例命令:

curl -X POST -H "Content-Type: application/json" -d '{"name":"admin","pwd":"123456"}' http://localhost:8080/login

如果返回登录成功,则表示登录接口测试通过。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愚公搬程序

你的鼓励将是我们最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值