0 / 0 / 0
Регистрация: 11.03.2020
Сообщений: 2
|
|
|
|
Spring. Передать данные из валидатора в представление
16.01.2021, 11:50. Показов 2623. Ответов 0
Модель
| Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
| package com.luchkin.blogAfkArena.model;
import javax.persistence.*;
import javax.validation.constraints.Size;
@Entity
public class MyUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "first_name")
private String first_name;
@Column(name = "last_name")
private String last_name;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Transient
private String checking_password;
@Column(name = "role")
private String role;
public MyUser() {
}
public MyUser(String first_name, String last_name, String email, String password, String checking_password) {
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.password = password;
this.checking_password = checking_password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getChecking_password() {
return checking_password;
}
public void setChecking_password(String checking_password) {
this.checking_password = checking_password;
}
} |
|
Контролер
| Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| package com.luchkin.blogAfkArena.controllers;
import com.luchkin.blogAfkArena.model.MyUser;
import com.luchkin.blogAfkArena.service.MyUserService;
import com.luchkin.blogAfkArena.validator.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
@Controller
public class AuthenticationController {
@Autowired
public MyUserService myUserService;
@Autowired
public UserValidator userValidator;
@GetMapping("/login")
public String getPageLogin(){
return "login/login";
}
@GetMapping(value = "/registration")
public String getPageRegistration(Model model){
model.addAttribute("myuser", new MyUser());
return "login/registration";
}
@PostMapping(value = "/registration")
public String pageRegistration(@ModelAttribute("myuser") MyUser myUser, BindingResult bindingResult, Model model){
userValidator.validate(myUser, bindingResult);
if(bindingResult.hasErrors()){
return "login/registration";
}
myUserService.save(myUser);
return "redirect:/home";
}
} |
|
Валидатор
| Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| package com.luchkin.blogAfkArena.validator;
import com.luchkin.blogAfkArena.model.MyUser;
import com.luchkin.blogAfkArena.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class UserValidator implements Validator {
@Autowired
private MyUserService myUserService;
@Override
public boolean supports(Class<?> aClass) {
return MyUser.class.equals(aClass);
}
@Override
public void validate(Object o, Errors errors) {
MyUser myUser = (MyUser) o;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "first_name", "Required:");
if(myUser.getFirst_name().length() < 2 || myUser.getFirst_name().length() > 18){
errors.rejectValue("first_name", "Имя должно быть не меньше 2 символов и не больше 18");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "last_name", "Required:");
if(myUser.getLast_name().length() < 2 || myUser.getLast_name().length() > 18){
errors.rejectValue("last_name", "Фамилия должна быть не меньше 2 символов и не больше 18");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "Required:");
if (myUser.getEmail().length() > 100){
errors.rejectValue("email", "Email должен быть меньше 100");
}
if (myUserService.findByEmail(myUser.getEmail()) != null){
errors.rejectValue("email", "Пользователь с таким Email уже существует");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "Required:");
if(myUser.getPassword().length() < 6 || myUser.getPassword().length() > 18){
errors.rejectValue("password", "Пароль должен быть больше 6 символов и меньше 18 символов");
}
if(!myUser.getPassword().equals(myUser.getChecking_password())){
errors.rejectValue("password", "Пароли не совпадают");
}
}
} |
|
| HTML5 | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| <!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Title</title>
</head>
<body>
<header th:insert="blocks/header :: header" ></header>
<div class="container">
<form th:method="post" th:object="${myuser}" th:action="@{/registration}">
<input type="text" th:field="*{first_name}" id="first_name" placeholder="Укажите имя" class="form-control"><br>
<input type="text" th:field="*{last_name}" id="last_name" placeholder="Укажите фамилию" class="form-control"><br>
<input type="text" th:field="*{email}" id="email" placeholder="Укажите электронную почту" class="form-control"><br>
<input type="text" th:field="*{password}" id="password" placeholder="Укажите пароль" class="form-control"><br>
<input type="text" th:field="*{checking_password}" id="checking_password" placeholder="Введите пароль повторно для проверки" class="form-control"><br>
<button type="submit" class="btn btn-success">Зарегистрироваться</button>
</form>
</div>
<footer th:insert="blocks/footer :: footer"></footer>
</body>
</html> |
|
Мне как то надо передать ошибки из валидатора в представление, если кто знает как это сделать помогите, это таймлиф, чтобы когда пользователь вводил не правильные значения, страница перезагружалась, и под инпутом была надпись из валидатора
0
|