下面就为你讲解如何使用Spring和MongoDB实现登录注册功能。
准备工作
- 安装并启动MongoDB服务器
- 创建Maven项目,引入所需依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
实现注册功能
- 编写User类用来保存用户信息,包含用户名和密码字段
```java
@Data
@Document(collection = "user")
public class User implements UserDetails {
@Id
private String id;
private String username;
private String password;
private boolean accountNonExpired = true;
private boolean accountNonLocked = true;
private boolean credentialsNonExpired = true;
private boolean enabled = true;//省略方法
}
2 .编写UserController实现注册
java
@RestController
@RequestMapping("/user")
public class UserController {private final BCryptPasswordEncoder passwordEncoder; private final UserService userService; public UserController(UserService userService, BCryptPasswordEncoder passwordEncoder) { this.userService = userService; this.passwordEncoder = passwordEncoder; } @PostMapping("/register") public ResponseEntity<User> register(@RequestBody User user) { String encodedPassword = passwordEncoder.encode(user.getPassword()); user.setPassword(encodedPassword); User newUser = userService.saveUser(user); return ResponseEntity.ok(newUser); }
}
3. 编写UserService,其中saveUser用于将用户信息保存到MongoDB中
java
@Service
public class UserServiceImpl implements UserService, UserDetailsService {private final UserRepository userRepository; public UserServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; } @Override public User saveUser(User user) { return userRepository.save(user); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUsername(username); if (user == null) { throw new UsernameNotFoundException("用户不存在"); } return user; }
}
4. 编写UserRepository,使用Spring Data MongoDB来进行数据库操作
java
public interface UserRepository extends MongoRepository{
User findByUsername(String username);
}
```
实现登录功能
- 在Spring Security配置类中配置使用UserDetailsService进行身份认证
```java
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {private final UserService userService; @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); } //省略其他配置
}
2. 编写登录接口
java
@RestController
@RequestMapping("/user")
public class UserController {//省略其他代码 @PostMapping("/login") public ResponseEntity<String> login(HttpServletRequest request, @RequestParam String username, @RequestParam String password) { try { request.login(username, password); } catch (ServletException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } return ResponseEntity.ok("登录成功"); }
}
```
3. 编写登录页面和注册页面,使用表单提交用户名和密码的方式来进行登录和注册
综上所述,使用以上方式就可以在Spring和MongoDB中实现简单的登录注册功能。
示例:
- 在MongoDB中创建名为
test
的数据库,运行以下示例代码,创建用户名密码分别为test
、123456
的用户
```java
@RestController
@RequestMapping("/user")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/save")
public ResponseEntity<User> save() {
User user = new User();
user.setUsername("test");
user.setPassword("123456");
User newUser = userService.saveUser(user);
return ResponseEntity.ok(newUser);
}
}
```
- 使用Postman发送POST请求到
http://localhost:8080/user/register
,请求Body为以下JSON数据:
json
{
"username": "test",
"password": "123456"
}
若收到{"id":"xxx", "username":"test", "password":"$2a$10$xxx","accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true}
则表示注册成功。
- 配置Spring Security,使
/user/login
接口需要身份认证
```java
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
//省略其他代码
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/user/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll();
}
}
```
- 使用Postman发送POST请求到
http://localhost:8080/user/login?username=test&password=123456
,若收到登录成功
则表示登录成功。
以上就是使用Spring和MongoDB实现登录注册功能的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Spring+MongoDB实现登录注册功能 - Python技术站