Hướng dẫn validate form trong Spring WebMVC

2023-06-13 18:15:39

Hướng dẫn validate form trong Spring WebMVC 

Bước 1: Mở Eclipse Chọn File->New -> Dynamic Web Project 

Chú ý: Trong bước này nhớ tạo Target runtime cho nó.

Chọn Next à Next à Tích chọn “Generate web.xml deployment descriptor”  ->Finish

Bước 2: Convert to maven project

Click phải vào project à Configure à Convert to Maven Project à Finish

Bước 3: Thêm các thư viện cho ứng dụng trong file pom.xml

Để thực hiện validate ta dùng thêm các thư viện sau: 

    • spring web mvc
    • validation-api
    • hibernate-validator

file pom.xml

 

<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>
  <groupId>validateFormSpring</groupId>
  <artifactId>validateFormSpring</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
  <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.18</version>
</dependency>

  <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
	<dependency>	
	    <groupId>javax.validation</groupId>
	    <artifactId>validation-api</artifactId>
	    <version>2.0.1.Final</version>
	</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.0.Final</version>
</dependency>

		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

  </dependencies> 
   <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version>
        <configuration>
          <release>17</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
      </plugin>
    </plugins>
  </build>
</project>

Bước 4: Cấu hình file web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>validateFormSpring</display-name>
<servlet> 

  	<servlet-name>validateFormSpring</servlet-name> 

  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 

  	<init-param> 

  		<param-name>contextConfigLocation</param-name> 

  		<param-value>/WEB-INF/config/spring-config.xml</param-value> 

  	</init-param> 

  </servlet> 

  <servlet-mapping> 

  	<servlet-name>validateFormSpring</servlet-name> 

  	<url-pattern>/</url-pattern> 

  </servlet-mapping> 

</web-app>

Bước 5: Tạo file cấu hình spring-config.xml

Trong thư mục WEB-INF tạo thư mục config tạo file spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 

    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
    "> 

  <context:component-scan base-package="controllers" /> 
	<mvc:annotation-driven></mvc:annotation-driven>
	
	
  <bean 

    class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 

    <property name="prefix"> 

      <value>/views/</value> 

    </property> 

    <property name="suffix"> 

      <value>.jsp</value> 

    </property> 

  </bean> 
	 
</beans>

Bước 6: Tạo class entity Account 

tạo thư mục entity/ tạo class Account

package entities;

import java.util.Date;

import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Length;


public class Account {
	@NotEmpty(message = "fullname không rỗng nhé")
	private String fullName;
	
	@NotEmpty(message = "email không rỗng nhé")
	@Email(message = "email không đúng định dạng")
	private String email;
	

	@NotBlank(message = "password không rỗng nhé")
	private String password;

	@NotEmpty(message = "phone không rỗng nhé")
	private String phone;
	
	@NotNull(message = "birthday không rỗng nhé")
	private Date birthday;

	
	public Account() {
		// TODO Auto-generated constructor stub
	}


	public Account(@NotEmpty(message = "fullname không rỗng nhé") String fullName,
			@NotEmpty(message = "email không rỗng nhé") @Email(message = "email không đúng định dạng") String email,
			@NotBlank(message = "password không rỗng nhé") String password,
			@NotEmpty(message = "phone không rỗng nhé") String phone,
			@NotNull(message = "birthday không rỗng nhé") Date birthday) {
		super();
		this.fullName = fullName;
		this.email = email;
		this.password = password;
		this.phone = phone;
		this.birthday = birthday;
	}


	public String getFullName() {
		return fullName;
	}


	public void setFullName(String fullName) {
		this.fullName = fullName;
	}


	public String getEmail() {
		return email;
	}


	public void setEmail(String email) {
		this.email = email;
	}


	public String getPassword() {
		return password;
	}


	public void setPassword(String password) {
		this.password = password;
	}


	public String getPhone() {
		return phone;
	}


	public void setPhone(String phone) {
		this.phone = phone;
	}


	public Date getBirthday() {
		return birthday;
	}


	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
	
	

}

Bước 7: Tạo trang add.jsp trong thư mục webapp/views

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body>

<div class="container">
<div class="col-lg-6">
<f:form action="insertAccount" method="POST" modelAttribute="acc">
 <div class="form-group">
    <label for="exampleInputEmail1">FullName</label>
    <f:input type="text" class="form-control" path="fullName"/>
    <f:errors cssClass="text-danger" path="fullName">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <f:input type="text" class="form-control" path="email"/>
    <f:errors cssClass="text-danger" path="email">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <f:input type="password" class="form-control" path="password" />
    <f:errors cssClass="text-danger" path="password">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Phone</label>
    <f:input type="text" class="form-control" path="phone"/>
     <f:errors cssClass="text-danger" path="phone">
    	
    </f:errors>
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1">Birthday</label>
    <f:input type="date" class="form-control" path="birthday"/>
    <f:errors cssClass="text-danger" path="birthday">
    	
    </f:errors>
  </div>
  
  <button type="submit" class="btn btn-primary">Submit</button>
</f:form>
</div>
</div>
	
</body>
</html>

Bước 8: Tạo class AccountController

trong thư mục controllers

package controllers;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import entities.Account;

@Controller
public class AccountController {
	@InitBinder
    public void initBinder(WebDataBinder data) {
        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd");
        s.setLenient(false);
        data.registerCustomEditor(Date.class, new CustomDateEditor(s, true));
    }
    

	@GetMapping({"/","/insertAccount"})
	public String addAccount(Model model) {
		Account account = new Account();
		model.addAttribute("acc", account);
		return "add";
	}
	
	@PostMapping("insertAccount")
	public String insertAccount(@Valid @ModelAttribute("acc") Account acc,BindingResult result, HttpSession session,Model model) {
		
		if(result.hasErrors()) {
			return "add";
		} else {
			return "ok";
		}
	
	}
}

Bước 11 tạo view ok.jsp để hiển thị

Bài viết liên quan

Ngày đăng : 2023-08-31 08:48:49
Spring MVC Custom Validation(Hướng dẫn validate file)

Spring MVC Custom Validation- Hướng dẫn validate file multipart file, custome anotation validate, validate file không rỗng , validate định dạng file.....

Read More
Ngày đăng : 2023-07-26 17:12:59
Hướng dẫn sử dụng i18n Internationalization(Quốc tế hóa) làm đa ngôn ngữ trong Spring MVC

Sử dụng i18n Internationalization(Quốc tế hóa) làm đa ngôn ngữ trong ứng dụng web với Spring MVC

Read More
Ngày đăng : 2023-07-20 17:17:45
Tải giao diện Admin LTE

Tải giao diện Admin LTE 2 bản rút gọn nhẹ làm trang quản trị cho ứng dụng web ...............

Read More
Ngày đăng : 2023-06-22 11:15:11
Hướng dẫn CRUD Spring WebMVC vs Hibernate phần 2 (Quản lý sản phẩm)

Hướng dẫn CRUD Spring WebMVC vs Hibernate phần 2 (Quản lý sản phẩm), CRUD có upload image và có quan hệ khóa ngoại

Read More
Ngày đăng : 2023-06-20 10:30:47
Hướng dẫn CRUD (Thêm sửa xóa) Spring WebMVC vs Hibernate

Hướng dẫn Thêm sửa xóa dữ liệu với spring webmvc sử dụng hibernate , trong bài viết này mình sử dụng database oracle

Read More
Ngày đăng : 2023-06-13 18:25:02
Hướng dẫn upload file trong spring webmvc

Hướng dẫn upload file trong spring webmvc sử dụng common-io, common-fileupload ...

Read More
Ngày đăng : 2023-06-08 14:57:17
Tổng quan về Spring Framework và Spring MVC

Là một framework phát triển ứng dụng phổ biến nhất cho ứng dụng doanh nghiệp trong Java Là một nền tảng Java mã nguồn mở. Được viết đầu tiên bởi Rod Johnson và được phát hành lần đầu dưới phiên bản Apache 2.0 vào tháng 6 năm 2003

Read More