Table of Contents
The structure of Demo in Eclipse
Home Java javaTutorial How to use WebDataBinder in Spring?

How to use WebDataBinder in Spring?

Jul 18, 2017 am 09:56 AM
spring web

It’s still the same old rules, straight to the point. When we develop, we often pass parameters from html and jsp to the background. However, one situation we often encounter is that the passed data needs to be assembled into an object format in the background. The most common one is the enum type. At this time, the @initBinder annotation provided by spring plays a great role.

In the following example, we create a JavaBean (username, password, email and date of birth of a user), and we create two custom validation classes .The first one, we verify the user name and password. The second one, verify the email address,

The structure of Demo in Eclipse


Validator is an interface with two methods;
boolean supports( Class clazz) : Instance class to check whether the parameters are successfully verified;
void validate(Object target, Errors errors) : If supports() method Return true, the target object is legal. Errors.rejectValue() The method registers error information with a field name;

Uservalidator.java
##
 1 package com.concretepage.validators; 2 import org.springframework.stereotype.Component; 3 import org.springframework.validation.Errors; 4 import org.springframework.validation.ValidationUtils; 5 import org.springframework.validation.Validator; 6 import com.concretepage.User; 7 @Component 8 public class UserValidator implements Validator  { 9     @Override10     public boolean supports(Class<?> clazz) {11         return User.class.isAssignableFrom(clazz);12     }13     @Override14     public void validate(Object target, Errors errors) {15         User user = (User)target;16         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "","Username is empty");17         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "", "Password is empty");18         if (user.getName().length()<5) {19             errors.rejectValue("name","", "Username length is less than 5");20         }21     }22 }
Copy after login
UserValidator.java
EmailValidator.java
 1 package com.concretepage.validators; 2 import org.springframework.stereotype.Component; 3 import org.springframework.validation.Errors; 4 import org.springframework.validation.ValidationUtils; 5 import org.springframework.validation.Validator; 6 import com.concretepage.User; 7 @Component 8 public class EmailValidator implements Validator { 9     @Override10     public boolean supports(Class<?> clazz) {11         return User.class.isAssignableFrom(clazz);12     }13     @Override14     public void validate(Object target, Errors errors) {15         User user = (User)target;16         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "","Email is empty");17         if (!user.getEmail().contains("@")) {18             errors.rejectValue("email","", "Email is not valid.");19         }20     }21 }
Copy after login
EmailValidator.java
##User.java
##
 1 package com.concretepage;
 2 import java.util.Date;
 3 public class User {
 4     private String name;
 5     private String password;
 6     private String email;
 7     private Date dob;
 8     public String getName() {
 9         return name;
10     }
11     public void setName(String name) {
12         this.name = name;
13     }
14     public String getPassword() {
15         return password;
16     }
17     public void setPassword(String password) {
18         this.password = password;
19     }
20     public String getEmail() {
21         return email;
22     }
23     public void setEmail(String email) {
24         this.email = email;
25     }
26     public Date getDob() {
27         return dob;
28     }
29     public void setDob(Date dob) {
30         this.dob = dob;
31     }
32 }
Copy after login
User.java
MyWorldController
 1 package com.concretepage; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4  5 import javax.validation.Valid; 6  7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.beans.propertyeditors.CustomDateEditor; 9 import org.springframework.stereotype.Controller;10 import org.springframework.ui.ModelMap;11 import org.springframework.validation.BindingResult;12 import org.springframework.web.bind.WebDataBinder;13 import org.springframework.web.bind.annotation.InitBinder;14 import org.springframework.web.bind.annotation.ModelAttribute;15 import org.springframework.web.bind.annotation.RequestMapping;16 import org.springframework.web.bind.annotation.RequestMethod;17 import org.springframework.web.servlet.ModelAndView;18 19 import com.concretepage.validators.EmailValidator;20 import com.concretepage.validators.UserValidator;21 @Controller22 @RequestMapping("/myworld")23 public class MyWorldController {24     @Autowired25     private UserValidator userValidator;26     @Autowired27     private EmailValidator emailValidator;28 29     @RequestMapping(value="signup", method = RequestMethod.GET)30     public ModelAndView user(){31         return new ModelAndView("user","user",new User());32     }33     @InitBinder34     public void dataBinding(WebDataBinder binder) {35         binder.addValidators(userValidator, emailValidator);36         SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");37         dateFormat.setLenient(false);38         binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(dateFormat, true));39     }40     41     @RequestMapping(value="save", method = RequestMethod.POST)42     public String createUser(@ModelAttribute("user") @Valid User user,BindingResult result, ModelMap model) {43         if(result.hasErrors()) {44             return "user";45         }46         System.out.println("Name:"+ user.getName());47         System.out.println("Email:"+ user.getEmail());48         System.out.println("Date of Birth:"+ user.getDob());49         model.addAttribute("msg", "Welcome to My World!");50         return "success";51     }    
52 }
Copy after login
MyWorldController
Page Form
  <form:form action="save" method="post" commandName="user"><tr>  <td>User Name:</td> <td><form:input  path="name"/> </td> 
          <td> <form:errors path="name" cssStyle="color: red;"/></td> </tr><tr> <td> Password :</td> <td><form:input path="password"/> </td> 
         <td> <form:errors path="password" cssStyle="color: red;"/> </td> </tr><tr> <td>  Email :</td> <td><form:input path="email"/> </td> 
         <td> <form:errors path="email" cssStyle="color: red;"/> </td> </tr><tr> <td>  Date of Birth :</td> <td><form:input path="dob"/> </td> 
         <td> <form:errors path="dob" cssStyle="color: red;"/> </td> </tr>         <tr> <td colspan=3>   <input type="submit"> </td>
  </form:form>
Copy after login

 

The above is the detailed content of How to use WebDataBinder in Spring?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

How to set transaction isolation level in Spring How to set transaction isolation level in Spring Jan 26, 2024 pm 05:38 PM

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Spring Annotation Revealed: Analysis of Common Annotations Spring Annotation Revealed: Analysis of Common Annotations Dec 30, 2023 am 11:28 AM

Spring is an open source framework that provides many annotations to simplify and enhance Java development. This article will explain commonly used Spring annotations in detail and provide specific code examples. @Autowired: Autowired @Autowired annotation can be used to automatically wire beans in the Spring container. When we use the @Autowired annotation where dependencies are required, Spring will find matching beans in the container and automatically inject them. The sample code is as follows: @Auto

Spring Security permission control framework usage guide Spring Security permission control framework usage guide Feb 18, 2024 pm 05:00 PM

In back-end management systems, access permission control is usually required to limit different users' ability to access interfaces. If a user lacks specific permissions, he or she cannot access certain interfaces. This article will use the waynboot-mall project as an example to introduce how common back-end management systems introduce the permission control framework SpringSecurity. The outline is as follows: waynboot-mall project address: https://github.com/wayn111/waynboot-mall 1. What is SpringSecurity? SpringSecurity is an open source project based on the Spring framework, aiming to provide powerful and flexible security for Java applications.

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

See all articles