要實現用戶注冊功能,可以按照以下步驟進行:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true)
private String username;
private String password;
@Column(unique = true)
private String email;
// 省略其他屬性和方法
}
public class SignupRequest {
private String username;
private String password;
private String email;
// 省略getter和setter方法
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void registerUser(SignupRequest signupRequest) {
// 創建新用戶
User user = new User();
user.setUsername(signupRequest.getUsername());
user.setPassword(signupRequest.getPassword());
user.setEmail(signupRequest.getEmail());
// 保存用戶到數據庫
userRepository.save(user);
}
}
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private UserService userService;
@PostMapping("/signup")
public ResponseEntity<String> signup(@RequestBody SignupRequest signupRequest) {
userService.registerUser(signupRequest);
return ResponseEntity.ok("User registered successfully!");
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtRequestFilter jwtRequestFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/signup").permitAll()
.anyRequest().authenticated()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}
這樣,當用戶發送POST請求到/api/auth/signup
接口時,會調用AuthController
的signup
方法來處理用戶注冊請求。在該方法中,會調用UserService
的registerUser
方法來完成實際的注冊邏輯。