Implementing User Sign Up in Vaadin Flow Applications (Simple)
An experienced developer gives a tutorial on creating a simple implementation of user registration (sign up) in Vaadin Flow Java web applications.
Join the DZone community and get the full member experience.
Join For FreeAfter sign in (or log in), sign up is probably the next logical use case in the user management workflow of a web application. In this article, I'll summarize the key points that I explain in detail in this video:
Implementing a Sign Up/Register View
A good first step in implementing user sign-up is to add a view so you can test the implementation as you code it. The view should include the required fields to create a user in your database and (if you are using passwords), an extra field to confirm the password, and the logic to validate the input. All the logic for registering the user should be delegated to a service class. Here's an example:
xxxxxxxxxx
"register") (
public class RegisterView extends Composite {
private final AuthService authService;
public RegisterView(AuthService authService) {
this.authService = authService;
}
protected Component initContent() {
TextField username = new TextField("Username");
PasswordField password1 = new PasswordField("Password");
PasswordField password2 = new PasswordField("Confirm password");
return new VerticalLayout(
new H2("Register"),
username,
password1,
password2,
new Button("Send", event -> register(
username.getValue(),
password1.getValue(),
password2.getValue()
))
);
}
private void register(String username, String password1, String password2) {
if (username.trim().isEmpty()) {
Notification.show("Enter a username");
} else if (password1.isEmpty()) {
Notification.show("Enter a password");
} else if (!password1.equals(password2)) {
Notification.show("Passwords don't match");
} else {
authService.register(username, password1);
Notification.show("Check your email.");
}
}
}
Implementing the Backend Service
In this example, the service job is to persist a new User
in the database. In later articles, I'll show you more sophisticated implementations. Here's the register
method:
x
public class AuthService {
public record AuthorizedRoute(String route, String name, Class<? extends Component> view) {
private final UserRepository userRepository;
public AuthService(UserRepository userRepository) {
this.userRepository = userRepository;
}
...
public void register(String username, String password) {
userRepository.save(new User(username, password, Role.USER));
}
}
Summary
This is the first iteration on implementing more realistic user sign-in in Vaadin Flow applications. In the next article, I'll show you how to generate activation links that you can send the user in order to complete the registration process.
Opinions expressed by DZone contributors are their own.
Comments