注册用户时,如果选择是管理员,需要输入验证密码,验证成功则注册成功spring代码前后端
时间: 2024-03-28 20:42:19 浏览: 72
这是一个比较复杂的功能,需要前后端协同实现,以下是一个基本的示例:
前端代码:
```html
<form id="register-form">
<input type="text" name="username" placeholder="用户名" required>
<input type="password" name="password" placeholder="密码" required>
<select name="role">
<option value="user">普通用户</option>
<option value="admin">管理员</option>
</select>
<input type="password" name="adminPassword" placeholder="管理员验证密码" required>
<button type="submit">注册</button>
</form>
<script>
const form = document.getElementById('register-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(form);
const response = await fetch('/register', {
method: 'POST',
body: formData
});
if (response.ok) {
alert('注册成功');
window.location.href = '/login';
} else {
const message = await response.text();
alert(message);
}
});
</script>
```
后端代码(使用 Spring Boot):
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/register")
public ResponseEntity<String> register(
@RequestParam("username") String username,
@RequestParam("password") String password,
@RequestParam("role") String role,
@RequestParam("adminPassword") String adminPassword) {
if ("admin".equals(role) && !"admin123".equals(adminPassword)) {
return ResponseEntity.badRequest().body("管理员验证密码错误");
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
user.setRole(role);
userService.save(user);
return ResponseEntity.ok("注册成功");
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void save(User user) {
userRepository.save(user);
}
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;
// getters and setters
}
public interface UserRepository extends JpaRepository<User, Long> {}
```
这段代码假设管理员验证密码是固定的 "admin123",如果需要更安全的验证密码,可以使用加密算法进行加密。
阅读全文