第四步,用户注册和登录
创建用户服务接口
         在src/main/java目录下创建com.example.hotelbookingsystem.service包,并在该包下创建UserService接口:
package com.example.hotelbookingsystem.service;import com.example.hotelbookingsystem.entity.User;public interface UserService {User register(User user);User login(String username, String password);
}
实现用户服务
        创建UserServiceImpl类实现UserService接口:
package com.example.hotelbookingsystem.service.impl;import com.example.hotelbookingsystem.entity.User;
import com.example.hotelbookingsystem.repository.UserRepository;
import com.example.hotelbookingsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserRepository userRepository;@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic User register(User user) {// 密码加密user.setPassword(passwordEncoder.encode(user.getPassword()));// 设置默认角色为顾客user.setRole("CUSTOMER");return userRepository.save(user);}@Overridepublic User login(String username, String password) {User user = userRepository.findByUsername(username);if (user != null && passwordEncoder.matches(password, user.getPassword())) {return user;}return null;}
}
代码解释:
- 使用@Autowired注入UserRepository和PasswordEncoder依赖。
- register()方法:- 使用passwordEncoder.encode()对密码进行加密。
- 设置默认角色为"CUSTOMER"。
- 使用userRepository.save()保存用户信息到数据库。
 
- 使用
- login()方法:- 使用userRepository.findByUsername()根据用户名查询用户。
- 使用passwordEncoder.matches()比较输入密码和数据库中加密后的密码是否一致。
- 如果用户名和密码都匹配,则返回用户信息,否则返回null。
 
- 使用
创建用户控制器
        在src/main/java目录下创建com.example.hotelbookingsystem.controller包,并在该包下创建UserController类:
package com.example.hotelbookingsystem.controller;import com.example.hotelbookingsystem.entity.User;
import com.example.hotelbookingsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@Res