携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情
登入注册模块设计
创建User类
我们先创建一个model包用来保存实体类
在其下创建User类!
package com.example.onlinemusic.model;
import lombok.Data;
/**
* Created with IntelliJ IDEA.
* Description:
* User: hold on
* Date: 2022-07-26
* Time: 13:37
*/
@Data //Data注解生成了setter/getter/tostring方法
public class User {
private int id;
private String username;
private String password;
}
创建对应的Mapper和Controller
创建UserMapper接口
创建Mapper包保存Mapper接口!
//UserMapper
package com.example.onlinemusic.mapper;
import com.example.onlinemusic.model.User;
import org.apache.ibatis.annotations.Mapper;
/**
* Created with IntelliJ IDEA.
* Description:
* User: hold on
* Date: 2022-07-26
* Time: 13:38
*/
@Mapper //实现xml映射,无需通过其他的mapper映射文件!
public interface UserMapper {
//登入功能!
User login(User loginUser);
}
创建UserMapper.xml
在resource包下创建mybatis包用于保存mapper.xml文件,再创建UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.onlinemusic.mapper.UserMapper">
<select id="login" resultType="com.example.onlinemusic.model.User">
select * from user where username=#{username} and password=#{password}
</select>
</mapper>
实现登入
设置登入的请求和响应
-
请求
请求: { post, //请求方法 /user/login //请求的url data:{username,password} //传输的数据! } -
响应
响应:
{
"status":0, //status 为0表示登入成功,为负数表示登入失败!
"message":"登入成功", // 放回登入信息!
"data":{ // 登入成功后获取到相应的用户信息!
"id":xxxx,
"username":xxxx,
"password":xxxx
}
}
创建UserController类
创建一个controller包,在其包下创建一个UserController类
package com.example.onlinemusic.controller;
import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* Created with IntelliJ IDEA.
* Description:
* User: hold on
* Date: 2022-07-26
* Time: 15:12
*/
@RestController // @ResponseBody + @Controller
@RequestMapping("/user") //设置路由 用来映射请求!
public class UserController {
//将UserMapper注入!
@Resource
private UserMapper userMapper;
@RequestMapping("/login")
public void login(@RequestParam String username,@RequestParam String password){
User userLogin = new User();
userLogin.setUsername(username);
userLogin.setPassword(password);
User user = userMapper.login(userLogin);
//先初步测试一下,后面再完善
if(user!=null){//登入成功!
System.out.println("登入成功!");
}else{
System.out.println("登入失败!");
}
}
}
这里只是粗略的写一下登入逻辑,然后验证是否可行,我们再进行后续代码的完善!
pastman验证登入功能
我们对照数据库中的user表中的数据!所以该登入请求成功!