停车场管理系统用户注册代码
时间: 2023-12-20 20:31:05 浏览: 40
以下是一个基于Spring Boot框架的停车场管理系统用户注册的代码示例:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpRequest signUpRequest) {
if(userService.existsByUsername(signUpRequest.getUsername())) {
return new ResponseEntity(new ApiResponse(false, "该用户名已被注册!"),
HttpStatus.BAD_REQUEST);
}
if(userService.existsByEmail(signUpRequest.getEmail())) {
return new ResponseEntity(new ApiResponse(false, "该邮箱已被注册!"),
HttpStatus.BAD_REQUEST);
}
// 创建新用户
User user = new User(signUpRequest.getName(), signUpRequest.getUsername(),
signUpRequest.getEmail(), signUpRequest.getPassword());
User result = userService.save(user);
URI location = ServletUriComponentsBuilder
.fromCurrentContextPath().path("/users/{username}")
.buildAndExpand(result.getUsername()).toUri();
return ResponseEntity.created(location).body(new ApiResponse(true, "用户注册成功!"));
}
}
```
上述代码中,我们使用了Spring Boot框架提供的@RestController和@RequestMapping注解来定义一个RESTful API接口。@PostMapping注解表示这是一个POST请求,请求的路径是“/api/register”。@Valid和@RequestBody注解用于验证请求体中的数据是否符合要求。如果验证失败,我们将返回一个HTTP状态码为400的错误响应。如果验证通过,我们将创建一个新的用户对象,并将其保存到数据库中。最后,我们将返回一个HTTP状态码为201的成功响应,其中包含了新用户的信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)