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

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

不言
Release: 2018-09-28 15:54:29
forward
1693 people have browsed it

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!

Related labels:
source:cnblogs.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template