post-image

[Thực hành] Validating Form Input

8. Validation

NỘI DUNG BÀI VIẾT

Mục tiêu

 Luyện tập validate các trường dữ liệu trong form.

Mô tả 

Trong phần này chúng ta sẽ phát triển chức năng cho phép validate thông tin của người dùng.

Chức năng này cho phép nhập vào thông tin người dùng và hiển thị các thông báo tương ứng với giá trị của các trường dữ liệu.

Yêu cầu đối với dữ liệu người dùng bao gồm:

  • Tên bắt buộc, có độ dài tối thiểu là 2 ký tự, tối đa là 30 ký tự
  • Tuổi bắt buộc, có giá trị nhỏ nhất là 18

Để hoàn thành bài thực hành, học viên cần:

  • Đưa mã nguồn lên GitHub
  • Dán link của repository lên phần nộp bài trên CodeGymX

Hướng dẫn

Bước 1: Tạo project Gradle với tên validate-infor-user

Bước 2: Thêm springframeword và validation dependencies trong file build.grade

compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
compile group: 'org.springframework', name: 'spring-core', version: '4.3.17.RELEASE'
compile group: 'org.springframework', name: 'spring-context', version: '4.3.17.RELEASE'
compile group: 'org.springframework', name: 'spring-beans', version: '4.3.17.RELEASE'
compile group: 'org.springframework', name: 'spring-web', version: '4.3.17.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.17.RELEASE'
compile group: 'org.thymeleaf', name: 'thymeleaf-spring4', version: '3.0.4.RELEASE'
compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
compile group: 'org.hibernate', name: 'hibernate-validator', version: '6.0.10.Final'

Bước 3:Tạo cấu trúc thư mục dự án như sau

Bước 4: Cấu hình cho dự án:

4.1. Thêm file ApplicationConfig cấu hình Thymeleaf và view

package com.codegym;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

@Configuration
@EnableWebMvc
@ComponentScan("com.codegym")
public class ApplicationConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    //Thymeleaf Configuration
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(applicationContext);
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }

    @Bean
    public TemplateEngine templateEngine() {
        TemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }

    @Bean
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }
}




4.2. Thêm file ApplicationInitializer

package com.codegym;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{ApplicationConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[0];
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

Bước 5: Tạo class User trong thư mục model như sau:

@NotEmpty: không để trống

@Size(min = 2, max = 30): độ dài từ 2 đến 30

@Min(18): Giá trị nhỏ nhất là 18

package com.codegym.model;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;

public class User {

    @NotEmpty
    @Size(min = 2, max = 30)
    private String name;

    @Min(18)
    private int age;

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Bước 6: Tạo controller UserController

Thêm @Validated @ModelAttribute(“user”) User user để xác thực Model User

Thêm

BindingResult bindingResult giữ kết quả xác nhận và ràng buộc User có xảy ra lỗi không.

package com.codegym.controller;

import com.codegym.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UserController {
    @GetMapping("/user")
    public ModelAndView showForm() {
        ModelAndView modelAndView = new ModelAndView("index");
        modelAndView.addObject("user", new User());
        return modelAndView;
    }

    @PostMapping("/validateUser")
    public ModelAndView checkValidation(@Validated @ModelAttribute("user") User user, BindingResult bindingResult) {
        if (bindingResult.hasFieldErrors()) {
            ModelAndView modelAndView = new ModelAndView("index");
            return modelAndView;
        }
        ModelAndView modelAndView = new ModelAndView("result");
        return modelAndView;
    }

}

Bước 7: Trong thư mục views tạo file

7.1. index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Form</title>
</head>
<body>
<form th:object="${user}" th:action="@{/validateUser}" method="post" >
    <table>
        <tr>
            <td>Name:</td>
            <td><input th:field="*{name}"></td>
            <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
        </tr>
        <tr>
            <td>Age:</td>
            <td><input th:field="*{age}"></td>
            <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name Error</td>
        </tr>
        <tr>
            <td>
                <button type="submit">Submit</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

7.2. result.html

<html>
<head>
    <title>Congratulations</title>
</head>
<body>
<h1>Congratulations! You are old enough to sign up for this site.</h1>
</body>
</html>

Bước 8: Cấu hình Artifact và Tomcat

Bước 9: Chạy ứng dụng và truy cập vào đường dẫn sau:

9.1. Nhập dữ liệu sai validate ta có thông báo

10.2. Nhập dữ liệu đúng ta đi tới trang result

Mã nguồn tham khảo: https://github.com/codegym-vn/validate-infor-user

Leave a Reply

Your email address will not be published.