What are the advantages of the SpringMVC architecture? ——Form and data validation (4)

foreword

insert image description here
"Author's Homepage" : Sprite Youbai Bubbles
"Personal Website" : Sprite's personal website
"Recommendation Column" :

Java one-stop service
React from entry to proficiency
Cool front-end code sharing
From 0 to hero, the road to Vue becoming a god
uniapp-from construction to promotion
From 0 to hero, Vue becoming a god Road
One column is enough to solve the algorithm
Let’s talk about the architecture from 0
The exquisite way of data circulation
The road to advanced backend

Please add a picture description


insert image description here

form data binding

Spring MVC provides a convenient mechanism to bind form data to JavaBean objects for validation and processing.
Form data binding is a very important mechanism in the Spring MVC framework, which allows developers to automatically bind form data in HTTP requests to JavaBean objects for verification and processing. This makes it easier for developers to write web applications while reducing the amount of duplicated code.

Below we will delve into the core concepts of Spring MVC form data binding and the corresponding Java code examples.

1. Form Data Binding:

In the Spring MVC framework, we can use the @ModelAttribute annotation to bind the form data in the HTTP request to the JavaBean object.

@Controller
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public ModelAndView register() {
    
    
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", new User());
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @PostMapping("/register")
    public String createUser(@ModelAttribute("user") User user, BindingResult result) {
    
    
        if (result.hasErrors()) {
    
    
            return "register";
        }
        userService.saveUser(user);
        return "redirect:/user/login";
    }
}

In the above example, we defined a view called "register" and added a new User object to the ModelAndView object in the GET request and returned it to the front end. In the POST request, we use the @ModelAttribute annotation to bind the form data in the HTTP request to the User object, and use the BindingResult object to validate the form data. If there is a validation error, we return to the "register" view; otherwise, we save the User object to the database and redirect to the "/user/login" path.

2. Form Validation:

In Spring MVC framework, we can use javax.validation and Spring Validation framework to validate form data.

@Controller
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public ModelAndView register() {
    
    
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", new User());
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @PostMapping("/register")
    public String createUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
    
    
        if (result.hasErrors()) {
    
    
            return "register";
        }
        userService.saveUser(user);
        return "redirect:/user/login";
    }
}

In the above example, we use the @Valid annotation to mark the User object in the createUser() method, and use the BindingResult object to receive the validation result. If there is a validation error, return to the "register" view; otherwise, save the User object to the database and redirect to the "/user/login" path.

3. Data type conversion (Type Conversion):

In the Spring MVC framework, we can use the @InitBinder annotation and the WebDataBinder class for data type conversion.

@Controller
@RequestMapping("/order")
public class OrderController {
    
    
    @Autowired
    private OrderService orderService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    
    
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @PostMapping("/create")
    public String createOrder(@ModelAttribute("order") Order order) {
    
    
        orderService.saveOrder(order);
        return "redirect:/order";
    }
}

In the above example, we use the @InitBinder annotation to define a method for data type conversion, which converts the Date type into a string in the specified format. In the createOrder() method, the Spring MVC framework will automatically bind the form data in the HTTP request to the Order object, and perform data type conversion as needed.

Through the above introduction, we can see that form data binding is a very important mechanism in the Spring MVC framework, which allows developers to automatically bind form data in HTTP requests to JavaBean objects for verification and processing . Only by deeply understanding the concept of form data binding and mastering the corresponding Java code skills can we flexibly use Spring MVC in actual development

Data validation

Spring MVC also provides an easy mechanism to validate form data. Validation rules can be easily defined by using annotations or XML configuration.
Data validation is a very important mechanism in the Spring MVC framework, which allows developers to verify that form data conforms to specified rules. Validation rules can be easily defined by using annotations or XML configuration.

Below we will delve into the core concepts of Spring MVC data validation and the corresponding Java code examples.

1. Data Validation:

In Spring MVC framework, we can use javax.validation and Spring Validation framework to validate form data.

public class User {
    
    
    @NotNull
    private String name;

    @Email
    private String email;

    @Size(min = 6, max = 20)
    private String password;

    // getters and setters
}

In the above example, we defined a JavaBean object named User and used annotations to mark the validation rules for each attribute. For example, the @NotNull annotation is used to verify whether the name attribute is empty; the @Email annotation is used to verify whether the email attribute conforms to the Email format; the @Size annotation is used to verify whether the length of the password attribute is within the range of [min, max].

2. Validator Configuration:

In the Spring MVC framework, we can use the LocalValidatorFactoryBean class to configure the validator.

@Configuration
public class ValidationConfig {
    
    
    @Bean
    public LocalValidatorFactoryBean validator() {
    
    
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
    
    
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
        processor.setValidator(validator());
        return processor;
    }
}

In the above example, we defined a ValidationConfig configuration class and defined two Beans in it: validator and methodValidationPostProcessor. Among them, validator Bean returns a LocalValidatorFactoryBean object for creating a validator; methodValidationPostProcessor Bean returns a MethodValidationPostProcessor object for enabling method-level validation.

3. Perform Validation:

In the Spring MVC framework, we can use the @Valid annotation to bind form data to JavaBean objects and automatically perform data validation.

@Controller
@RequestMapping("/user")
public class UserController {
    
    
    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public ModelAndView register() {
    
    
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", new User());
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @PostMapping("/register")
    public String createUser(@Valid @ModelAttribute("user") User user, BindingResult result) {
    
    
        if (result.hasErrors()) {
    
    
            return "register";
        }
        userService.saveUser(user);
        return "redirect:/user/login";
    }
}

In the above example, we use the @Valid annotation to mark the User object in the createUser() method, and use the BindingResult object to receive the validation result. If there is a validation error, return to the "register" view; otherwise, save the User object to the database and redirect to the "/user/login" path.

Through the above introduction, we can see that data verification is a very important mechanism in the Spring MVC framework, which allows developers to verify whether the form data conforms to the specified rules. Only by deeply understanding the concept of data validation and mastering the corresponding Java code skills can we flexibly use the Spring MVC framework in actual development to build efficient, reliable, and easy-to-maintain Web applications.

Guess you like

Origin blog.csdn.net/Why_does_it_work/article/details/132178146