Home Java javaTutorial Introduction to SpringMVC type conversion and verification methods (with code)

Introduction to SpringMVC type conversion and verification methods (with code)

Sep 28, 2018 pm 03:54 PM
springmvc

This article brings you an introduction to SpringMVC’s type conversion and verification methods (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Spring mvc data binding process:

SpringMvc passes the ServletRequest object and the formal parameter instance of the target method to the WebDataBinderFactory instance to create a DataBinder instance object. DataBinder calls the ConversionService component assembled in the SpringMvc context to perform type conversion and data formatting, and fills the Servlet request information into the formal parameter object. Call the Validator primary key to verify the validity of the selected data of the formal parameter object that has been bound to the request information, and finally generate the data binding result BindingData object. SpringMVC extracts the formal parameter object and verification error object in BindingResult and assigns them to the corresponding parameters of the processing method

We can see from the source code that the DataBinder object is created through WebDataBinderFactory

Custom type converter

When we encounter some special occasions, we may need to define our own type converter. Next, let’s explain a custom type converter that converts a string into an emp object. When the page cannot complete data binding or type conversion, springmvc will throw an exception. The exception information can be obtained using BindingResult.

Spring defines three types of converter interfaces. Any converter interface that implements it can be registered in ConversionServiceFactoryBean as a custom converter.

Convertre: Convert S type to T type.

ConverterFactory: Encapsulate multiple "homogeneous" Converters of the same series together. If you want to convert one type to another type and subclass objects (such as String to Number to Number's subclass ), you can use this converter

GenericConverter: Type conversion will be selected based on the contextual information in the host class where the source class object and the target class object are located.

package com.spring.mvc.controller;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class UserConverter implements Converter<String, User>{
    @Override
    public User convert(String source) {
        System.out.println(source);
        String users [] = source.split("-");
        User user = new User();
        user.setUno(Integer.valueOf(users[0]));
        user.setUsername(users[1]);
        user.setUserpass(users[2]);
        return user;
    }
}
Copy after login

ConversionService is the core interface of the type converter in SpringMVC. To add a custom type converter, you need to implement this interface/use ConversionServiceFactoryBean to create the first ConversionService in Spring's IOC container and configure it in the Bean properties. For the implementation class of the type converter, the type converter will be automatically called when SpringMvc handles the formal parameter binding of the method.

<!--将非mapping配置下的请求交给默认的Servlet来处理 -->
    <mvc:default-servlet-handler />
    <bean id="conversionService"
        class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <ref bean="userConverter" />
            </set>
        </property>
    </bean>
    <!-- 注册类型转换器 -->
    <mvc:annotation-driven conversion-service="conversionService" />
Copy after login

In actual development, you need to configure: tag

Data formatting

Input/output formatting of attributes, In essence, it still belongs to the category of type conversion. Spring defines a FarmattingConversionService implementation class that implements the ConversionService interface in the formatting module. This implementation class extends GenericConversionService, so it has both type conversion and formatting functions. FormattingConversionService has a FormattingConversionServiceFactoryBean factory class, which is used to construct the former. We want to register this

<mvc:annotation-driven conversion-service="FormattingConversionServiceFactoryBean" />
Copy after login

JSR303

jsr303 is the standard framework provided by java for bean data validity verification. It is already included in JavaEE6.0, and JSR303 passed Mark the Bean attributes with standard data such as @NotNull and @Max to specify verification rules, and verify the Bean through the marked verification interface.

@NotEmpty
    @NotNull
    private String name;
    
    @NotNull
    @NotEmpty
    private String age;
    
    @NotNull
    @NotEmpty
    @Email
    private String email;
Copy after login

We use the Form tag provided by SpringMVC at the front desk and use Form: errors path to bind attributes

@RequestMapping(value="/student",method=RequestMethod.POST)
    public String add(@Valid()Student student,BindingResult result){
        if (!result.hasErrors()) {//判断是否有格式转换错误或者其他校验没通过
            userService.addStudent(student);
            return "redirect:list";
        }else
            return "addPage";
    }
Copy after login

SpringMvc prompt message internationalization

<!-- 注册国际化信息,必须有id,指定资源文件名称,资源文件在src目录下 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="message"></property>
    </bean>
Copy after login

The above is the detailed content of Introduction to SpringMVC type conversion and verification methods (with code). 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)

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

What are the differences between SpringBoot and SpringMVC? What are the differences between SpringBoot and SpringMVC? Dec 29, 2023 am 10:46 AM

What is the difference between SpringBoot and SpringMVC? SpringBoot and SpringMVC are two very popular Java development frameworks for building web applications. Although they are often used separately, the differences between them are obvious. First of all, SpringBoot can be regarded as an extension or enhanced version of the Spring framework. It is designed to simplify the initialization and configuration process of Spring applications to help developers

What are the differences between spring and springmvc What are the differences between spring and springmvc Dec 29, 2023 pm 05:02 PM

The difference between spring and springmvc: 1. Positioning and functions; 2. Core functions; 3. Application areas; 4. Extensibility. Detailed introduction: 1. Positioning and functions. Spring is a comprehensive application development framework that provides dependency injection, aspect-oriented programming, transaction management and other functions. It is designed to simplify the development of enterprise-level applications, and Spring MVC is the Spring framework. A module in it is used for the development of Web applications and implements the MVC pattern; 2. Core functions and so on.

What is the difference between SpringBoot and SpringMVC? What is the difference between SpringBoot and SpringMVC? Dec 29, 2023 pm 05:19 PM

SpringBoot and SpringMVC are two frameworks commonly used in Java development. They are both provided by the Spring framework, but they have some differences in functions and usage methods. This article will introduce the characteristics and differences of SpringBoot and SpringMVC respectively. 1. Features of SpringBoot: Simplified configuration: SpringBoot greatly simplifies the project configuration process through the principle of convention over configuration. It can automatically configure the parameters required by the project, and developers

What are the differences between springboot and springmvc What are the differences between springboot and springmvc Jun 07, 2023 am 10:10 AM

The differences between springboot and springmvc are: 1. Different meanings; 2. Different configurations; 3. Different dependencies; 4. Different development times; 5. Different productivity; 6. Different ways to implement JAR packaging function; 7. Whether batch processing is provided Function; 8. Different functions; 9. Different community and documentation support; 10. Whether deployment descriptors are required.

How to use Java's SpringMVC interceptor How to use Java's SpringMVC interceptor May 13, 2023 pm 02:55 PM

The role of interceptor SpringMVC's interceptor is similar to the filter in Servlet development, which is used to pre-process and post-process the processor. Interceptors are connected into a chain in a certain order, and this chain is called an interceptor chain (InterceptorChain). When an intercepted method or field is accessed, the interceptors in the interceptor chain will be called in the order they were previously defined. Interceptors are also the specific implementation of AOP ideas. The difference between interceptors and filters: Filter (Filter) The scope of use of interceptor (Intercepter) is part of the servlet specification and can be used by any JavaWeb project. Spri

Using SpringMVC for Web service processing in Java API development Using SpringMVC for Web service processing in Java API development Jun 17, 2023 pm 11:38 PM

With the development of the Internet, Web services are becoming more and more common. As an application programming interface, JavaAPI is constantly launching new versions to adapt to different application scenarios. As a popular open source framework, SpringMVC can help us easily build web applications. This article will explain in detail how to use SpringMVC for Web service processing in JavaAPI development, including configuring SpringMVC, writing controllers, and using

Compare the similarities and differences between SpringBoot and SpringMVC Compare the similarities and differences between SpringBoot and SpringMVC Dec 29, 2023 am 08:30 AM

Analyzing the similarities and differences between SpringBoot and SpringMVC SpringBoot and SpringMVC are very important development frameworks in the Java field. Although they are both part of the Spring framework, there are some obvious differences in usage and functionality. This article will compare SpringBoot and SpringMVC and analyze the similarities and differences between them. First, let's learn about SpringBoot. SpringBo

See all articles