要实现用户注册功能,可以按照以下步骤进行:
@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
方法来完成实际的注册逻辑。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: tomcat怎么启动springboot项目