search
HomeJavajavaTutorialIntroduction to SpringMVC type conversion and verification methods (with code)

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;
    }
}

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" />

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" />

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;

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";
    }

SpringMvc prompt message internationalization

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

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
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools