How to implement user registration functionality using …

To enable user registration feature, you can follow these steps:

  1. Create a user entity class that includes the basic information of the user, such as username, password, email, etc.
@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;
    
    // 省略其他属性和方法
}
  1. Create a user registration request class to receive the registration information submitted by the user.
public class SignupRequest {
    private String username;
    private String password;
    private String email;
    
    // 省略getter和setter方法
}
  1. Create a user service class to handle user registration logic.
@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);
    }
}
  1. Create a user controller to handle user registration requests.
@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!");
    }
}
  1. Set up JWT authentication and permission control to ensure that only authenticated users can access the registration interface.
@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);
    }
}

Therefore, when a user sends a POST request to the /api/auth/signup endpoint, the signup method in the AuthController will be called to handle the user registration request. Within this method, the registerUser method in the UserService will be called to complete the actual registration process.

bannerAds