E
E
Elzee2020-05-05 18:05:56
Java
Elzee, 2020-05-05 18:05:56

How to validate user data?

I did a little registration for users, but I can’t do their validation, namely, I don’t know how to pass the Model attribute (in get or post) and what kind of object will be displayed in html.
Well type

model.addAttribute("form", сюда что-то надо добавить, но что? и в какой метод(get или post));


package com.steppedua.dropauto.controller;

import com.steppedua.dropauto.domain.RegistrationForm;
import com.steppedua.dropauto.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;

@Controller
@RequestMapping("/registration")
public class RegistrationController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;


//Сюда надо делать модель?
    @GetMapping
    public String registration(){
        return "registration";
    }

//Сюда надо делать модель?
    @PostMapping
    public String processUser(@Valid RegistrationForm form, Errors errors){
        if (errors.hasErrors()){
            return "registration";
        }
        //сохраняем зашифрованный пароль user
        userRepository.save(form.toUser(passwordEncoder));

        return "redirect:/login";
    }
}


package com.steppedua.dropauto.domain;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@Entity
@Data
@Table(name = "users")
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Login некорректный")
    @Size(min = 5, message = "минимум 5 символов")
    private String username;

    @NotBlank(message = "Password некорректный")
    @Size(min = 5, message = "минимум 5 символов")
    private String password;

    @Column(name = "email", unique = true)
    @Email(message = "Email некорректный")
    @NotBlank(message = "Email не может быть пустым")
    private String email;

    @NotBlank(message = "Номер телефона не может быть пустым")
    private String phone;

    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "roles")
    private Set<Role> roles = new HashSet<>();


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getRoles();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}


I made this class for easier user registration:

package com.steppedua.dropauto.domain;

import lombok.Data;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Collections;

@Data
public class RegistrationForm {

    @NotBlank(message = "Login некорректный")
    @Size(min = 5, message = "минимум 5 символов")
    private String username;

    @NotBlank(message = "password некорректный")
    @Size(min = 5, message = "минимум 5 символов")
    private String password;

    @Email(message = "Email некорректный")
    @NotBlank(message = "Email не может быть пустым")
    private String email;


    @NotBlank(message = "Номер телефона не может быть пустым")
    private String phone;


    public User toUser(PasswordEncoder passwordEncoder) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(passwordEncoder.encode(password));
        user.setPhone(phone);
        user.setUsername(username);
        user.setRoles(Collections.singleton(Role.USER));
        return user;
    }
}


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <title>Registration Page</title>
</head>
<body>
<h1>Registration Page</h1>

<form th:action="@{/registration}" th:object="${form}" method="post">
    <div>
        <label> User Name : <input type="text" th:filed="*{username}"/> </label>
        <span th:if="${#fields.hasErrors('username')}"
              th:errors="*{username}"></span>
    </div>
    <div>
        <label> Password: <input type="password" th:filed="*{password}"/> </label>
        <span class="invalid-feedback"
              th:if="${#fields.hasErrors('password')}"
              th:errors="*{password}"></span>
    </div>
    <div>
        <label> Email : <input type="text" th:filed="*{email}"/> </label>
        <span class="invalid-feedback"
              th:if="${#fields.hasErrors('email')}"
              th:errors="*{email}"></span>
    </div>
    <div>
        <label> Phone : <input type="text" th:filed="*{phone}"/> </label>
        <span class="invalid-feedback"
              th:if="${#fields.hasErrors('phone')}"
              th:errors="*{phone}"></span>
    </div>

    <div>
        <input class="btn btn-primary" type="submit" value="registration"/>
    </div>
</form>

</body>
</html>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question