我已经被困在这个问题上几个小时了,Spring Boot Controller方法是:@GetMapping
@GetMapping("/register")
public String showRegistrationForm(Model model, @RequestParam(required = false) boolean registrationError) {
UserRegistrationForm registrationForm = new UserRegistrationForm();
model.addAttribute("registrationForm", registrationForm);
model.addAttribute("registerError", registrationError);
return "registration";
}
和PostMapping:
@PostMapping("/register")
public String handleRegistration(@ModelAttribute @Valid UserRegistrationForm userRegistrationForm, BindingResult result, Model model) {
if(result.hasErrors()){
model.addAttribute("registrationForm", userRegistrationForm);
return "registration";
}
UserDTO userDTO = new UserDTO();
userDTO.setEmail(userRegistrationForm.getEmail());
userDTO.setPassword(passwordEncoder.encode(userRegistrationForm.getPassword()));
userDTO.setFirstName(userRegistrationForm.getFirstName());
userDTO.setLastName(userRegistrationForm.getLastName());
userDTO.setRoleName(Set.of("ROLE_USER"));
userDTO.setUsername(userRegistrationForm.getUsername());
User users = new User();
users.setUsername(userDTO.getUsername());
users.setEmail(userDTO.getEmail());
users.setPassword(userDTO.getPassword());
users.setFirstName(userDTO.getFirstName());
users.setLastName(userDTO.getLastName());
users.setRoleName(userDTO.getRoleName());
try {
userService.saveUser(users);
System.out.println(repository.findByEmail(users.getEmail()));
} catch (Exception e) {
if (repository.findByUsername(users.getUsername()).isPresent()
&& repository.findByEmail(users.getEmail()).isPresent()){
logger.warn(String.format("User already exists with the username: %s and the email: %s",
users.getUsername(), users.getEmail()));
throw new UserException(String.format("User already exists with the username: %s and the email: %s",
users.getUsername(), users.getEmail()));
} else if (repository.findByUsername(users.getUsername()).isPresent()) {
logger.warn(String.format("User already exists with the username: %s", users.getUsername()));
throw new UserException(String.format("User already exists with the username: %s", users.getUsername()));
} else if (repository.findByEmail(users.getEmail()).isPresent()) {
logger.warn(String.format("User already exists with the email: %s", users.getEmail()));
throw new UserException(String.format("User already exists with the email: %s", users.getEmail()));
}
}
return "redirect:/login?registrationSuccess=true";
}
我使用控制器建议来处理数据库验证,但是,这不是我遇到的问题。控制器通知处理我在底部抛出的错误@PostMapping.
百里香模板段:
<div class="d-flex flex-row align-items-center mb-4">
<i class="fas fa-user fa-lg me-3 fa-fw"></i>
<div class="form-outline flex-fill mb-0">
<label class="form-label" for="firstName">Name</label>
<input type="text" id="firstName" th:field="*{firstName}" class="form-control" placeholder="First name"/>
</div>
<div th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}" class="alert alert-warning"></div>
</div>
<div class="d-flex flex-row align-items-center mb-4">
<i class="fas fa-user fa-lg me-3 fa-fw"></i>
<div class="form-outline flex-fill mb-0">
<label class="form-label" for="lastName">Last name</label>
<input type="text" id="lastName" th:field="*{lastName}" class="form-control" placeholder="Last name"/>
</div>
<div th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}" class="alert alert-warning"></div>
</div>
我期待firstName和lastNameBindingResult要标记的字段然而,似乎没有一个被发送到模板。
RegistrationForm使用验证约束
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table
public class UserRegistrationForm {
@Id
@SequenceGenerator(name = "user_Reg_Form_Gen",
allocationSize = 1, sequenceName = "user_Reg_Form_Gen")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_Reg_Form_Gen")
Long registerFormID;
@NotNull(message = "Username is required")
@Size(min = 3, max = 16, message = "Username must be between 3 and 16 characters")
private String username;
@NotNull(message = "Please enter a password")
private String password;
private String matchPassword;
@NotNull(message = "First name is required")
private String firstName;
@NotNull(message = "Last name is required")
private String lastName;
@NotNull(message = "Email is required")
private String email;
}
感谢阅读:)
如果您想在username
和lastname
中有一些强制值,那么@NotNull
将不够。将它与@NotEmpty
结合起来,以便强制传递一些实际值,并且您不会从一些空的javascript输入文本表单中接收一些空字符串,这些字符串将通过验证。
@NotEmpty(message = "First name is required")
@NotNull(message = "First name is required")
private String firstName;
@NotEmpty(message = "Last name is required")
@NotNull(message = "Last name is required")
private String lastName;
您也可以将这些字符串字段的@NotEmpty
和@NotNull
与@NotBlank
结合起来。所以优化后的版本是
@NotBlank(message = "First name is required")
private String firstName;
@NotBlank(message = "Last name is required")
private String lastName;