您的位置:首页 > 新闻 > 会展 > 从零搭建Java酒店预订系统:实战指南_02

从零搭建Java酒店预订系统:实战指南_02

2024/10/9 15:09:30 来源:https://blog.csdn.net/weixin_37954941/article/details/140094772  浏览:    关键词:从零搭建Java酒店预订系统:实战指南_02

第四步,用户注册和登录

创建用户服务接口


        在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注入UserRepositoryPasswordEncoder依赖。
  • 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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com