注册

  • 请求参数有两个:username和password,分别表示用户名和密码。请求参数是通过URL传递的,如`/login?username=admin&password=123456
  • 响应数据: code(相应码,0表示成功,1表示失败)、message(响应消息)、data(响应数据)。
    1
    2
    3
    4
    5
    {
    "code": 0,
    "message": "登录成功",
    "data": null
    }
    定义一个有如上三个成员变量的result类,用于封装响应数据,spring自动将其转换为json格式返回给前端。

Result.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
private int code;
private String message;
private T data;

public static<E> Result<E> success(E data) {
return new Result<>(0, "success", data);
}

public static<E> Result<E> success() {
return new Result<>(0, "操作成功", null);
}

public static<E> Result<E> fail(int code, String message) {
return new Result<>(1, message, null);
}
}

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String nickname;
private String email;
private String avatar;
public Timestamp createTime;
public Timestamp updateTime;
}

UserMapper.java

1
2
3
4
5
6
7
8
9
@Mapper
public interface UserMapper {

@Select("select * from user where username = #{username}")
User findByUsername(String username);

@Insert("insert into user (username, password) values (#{username}, #{password})")
void add(String username, String encode);
}

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Service
public class UserServiceImpl implements UserService {

private UserMapper userMapper;
private PasswordEncoder passwordEncoder;

public UserServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder) {
this.userMapper = userMapper;
this.passwordEncoder = passwordEncoder;
}

@Override
public User findByUsername(String username) {
return userMapper.findByUsername(username);
}

@Override
public void register(String username, String password) {
//要进行加密处理,不能明文存储
String encode = passwordEncoder.encode(password);
userMapper.add(username, encode);
}
}

UserController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RestController
@RequestMapping("/user")
public class UserController {

private UserService userService;

public UserController(UserService userService) {
this.userService = userService;
}

@PostMapping
public Result register(String username, String password) {
//查询用户是否被占用
User u = userService.findByUsername(username);
if(u != null) {
return Result.fail(1, "用户名已被占用");
}else{
userService.register(username, password);
return Result.success();
}
}
}

由于密码不能明文存储,所以要进行加密处理,这里使用Spring Security提供的PasswordEncoder接口来进行加密处理。

在config包下创建一个SecurityConfig类,用于配置Spring Security。

1
2
3
4
5
6
7
8
@Configuration
public class SecurityConfig {

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}