Selamlar, bu yazımda Spring MVC’de form input’larını doğrulama işlemlerini inceleyeğiz.
Spring ile Form Input, Spring Framework kullanılarak web uygulamalarında kullanıcıdan veri girişi almak için oluşturulan web formlarının işlenmesini sağlayan bir mekanizmayı ifade eder. Spring, bu form verilerini alarak işleme, doğrulama ve veritabanına kaydetme gibi işlemleri kolaylaştırır ve güvenli bir şekilde işler.
Bağımlılıkları Tanımlayalım
Bağımlılıklarımızı Spring MVC için seçeceğiz. Bunun için de Spring Web, Validation ve Thymeleaf seçmemiz yeterli. Ben ek olarak Lombok‘u da ekleyeceğim. Şimdi pom.xml dosyamıza göz atalım:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> </parent> <groupId>com.codingbytime</groupId> <artifactId>form-validate</artifactId> <version>0.0.1-SNAPSHOT</version> <name>form-validate</name> <description>Validating Form Input</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
RegisterForm Oluşturalım
Validation işlemlerimiz için bir kayıt formu oluşturalım. Instance variable olarak firstName, lastName, email ve age olsun.
@Getter @Setter public class RegisterForm { @NotNull(message = "firstName can not be null") @Size(min = 2, max = 30) private String firstName; @NotNull(message = "lastName can not be null") @Size(min = 2, max = 30) private String lastName; @NotNull(message = "email can not be null") @Size(min = 5, max = 30) private String email; @NotNull(message = "age can not be null") @Min(value = 18, message = "yaş 18'den küçük olamaz") @Max(value = 40, message = "yaş 40'dan büyük olamaz") private Integer age; }
Controller Oluşturalım
Controller içerisinde GetMapping ve PostMapping olsun. GetMapping form alanımızı gösterirken, PostMapping form’a göndereceğimiz request’leri handle etsin. Ayrıca result sayfası için yeni bir controller oluşturmadan ViewController ile bunu set edelim.
@Controller public class FormController implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/results").setViewName("results"); } @GetMapping public String showForm(RegisterForm registerForm) { return "form"; } @PostMapping public String checkPersonInfo(@Valid RegisterForm registerForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "form"; } return "redirect:/results"; } }
HTML Dosyalarımızı Oluşturalım
- form.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Register Form</title> </head> <body> <body> <form action="#" th:action="@{/}" th:object="${registerForm}" method="post"> <table> <tr> <td>Firstname:</td> <td><input type="text" th:field="*{firstName}"/></td> <td th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}">***</td> </tr> <tr> <td>Lastname:</td> <td><input type="text" th:field="*{lastName}"/></td> <td th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}">***</td> </tr> <tr> <td>Email:</td> <td><input type="email" th:field="*{email}"/></td> <td th:if="${#fields.hasErrors('email')}" th:errors="*{email}">***</td> </tr> <tr> <td>Age:</td> <td><input type="number" th:field="*{age}"/></td> <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">***</td> </tr> <tr> <td> <button type="submit">Submit</button> </td> </tr> </table> </form> </body> </body> </html>
- result.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Result</title> </head> <body> Successfully Registered! </body> </html>
Çalıştıralım
Form’umuzu boş şekilde gönderdiğimiz de kontrollerimizin doğru çalıştığına emin olalım:
Verileri doğru gönderdiğimizde ise gelen result sayfası: