L
L
Leo Sobolev2021-05-07 15:11:13
Spring
Leo Sobolev, 2021-05-07 15:11:13

How to add input validation in spring boot application?

Good afternoon, Habr! I'm having a problem while developing an application for an internship at a university. I am making an application for working with a database (deleting, adding, editing, viewing). You need to add input checks to the application (when, let’s say, I add a user, if I entered the name incorrectly (I used numbers, more characters than it is written in the database, etc.). But when I googled, I didn’t find anything sensible and decided to contact you.
DBMS: PostgreSQL
Spring Boot
Maven
Mustache

Here is an example client entity:

package com.example.karakum.persist.entity;

import com.sun.istack.NotNull;
import lombok.Getter;
import lombok.Setter;

import javax persistence.*;
import java.io.Serializable;
import java.util.List;

@Getter
@Setter
@Entity
@Table(name="Client")
public class ClientEntity implements Serializable {
private static final long serialVersionUID = 4364632587002683208L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Basic(optional = false)
@Column(name = "Client_id", unique = true, nullable = false)
private Integer clientId;

@Column(name = "client_fn")
@NotNull
private String clientFn;

@Column(name = "client_passport")
private String clientPassport;

@Column(name = "client_bank")
private String clientBank;

@Column(name = "client_banknum")
private String clientBankNum;

@Column(name = "client_sign")
private String clientSign;

/* @OneToMany(mappedBy = "client")
private List contracts;
*/
public ClientEntity() {
}

public ClientEntity(String clientFn, String clientPassport, String clientBank, String clientBankNum, String clientSign) {
this.clientFn = clientFn;
this.clientPassport = clientPassport;
this.clientBank = clientBank;
this.clientBankNum = clientBankNum;
this.clientSign = clientSign;
}
}


Here is adding a client to the controller class:

@GetMapping(value = {"/clients/add"})
public String clientAdd(Model model) {
return "clientadd";
}

@PostMapping({"/clients/add"})
public String clientEntityAdd(@RequestParam String clientfn, @RequestParam String clientpassport, @RequestParam String clientbank, @RequestParam String clientbanknum, @RequestParam String clientsign, Model model) {
ClientEntity clientEntity = new ClientEntity(clientfn, clientpassport, clientbank, clientbanknum, clientsign);
clientRepository.save(clientEntity);
return "clientadd";
}


60952f974d859867637963.jpeg
This is how the page for adding a client looks like. I need errors to be generated when the input is incorrect

. Thank you in advance for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2021-05-07
@notbugbutfeature

Good afternoon!
It's usually done like this:
1) Add either a spring boot validation - https://www.baeldung.com/spring-boot-bean-validation
2) Create a DTO. For example, if you have a User entity, then also create a UserRequestDto.
For example,

UserRequestDto {
@NotBlank(message = "Name is mandatory")
String username;

@NotBlank(message = "Email is mandatory")
String email;
}

3) Validate the data sent to the backend (dto) using the above library and if something is wrong, throw a MethodArgumentNotValidException exception,
for example,
//@RestController
@Controller 
UserController {

public ResponseEntity<User> addUser( @Valid UserDto user ) {
// конвертируем UserDto -> User и в передаем в сервисный класс для сохранения
}

}

Validation can also be done on the client side using JavaScript or HTML.
By means of html, you can add required for inputs, specify the input type, for example, <input type="email" />
PS By the way, you have NotNull imported into your entity import com.sun.istack.NotNull;, but there should be a hibernate validator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question