特殊校验不能加到web层。
Validator和DataBinder组成了validation包, 主要用于但不限于MVC框架。
3.3 错误信息的处理代码
3.4 Bean操作和 BeanWrapper
3.4.1 得到基本的和嵌套的属性
Expression
Explanation
name
Indicates the property name corresponding to the methods getName() or isName() and setName(..)
account.name
Indicates the nested property name of the property account corresponding e.g. to the methods getAccount().setName() or getAccount().getName()
account[2]
Indicates the third element of the indexed property account. Indexed properties can be of type array, listor other naturally ordered collection
account[COMPANYNAME]
Indicates the value of the map entry indexed by the key COMPANYNAME of the Map property account
实例:
1. Employee 类: name,salary
2. Company类 name,managingDirector ; managingDirector是一个Employee对象
/**
* @Title: Employee.java
* @Package com.oscar999.valid
* @Description: TODO
* @author oscar999
* @date Sep 3, 2018 4:25:22 PM
* @version V1.0
*/
package com.oscar999.valid;
/**
* @ClassName: Employee
* @Description: TODO
* @author oscar999
*/
public class Employee {
private String name;
private float salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
/**
* @Title: Company.java
* @Package com.oscar999.valid
* @Description: TODO
* @author oscar999
* @date Sep 3, 2018 4:24:29 PM
* @version V1.0
*/
package com.oscar999.valid;
/**
* @ClassName: Company
* @Description: TODO
* @author oscar999
*/
public class Company {
private String name;
private Employee managingDirector;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Employee getManagingDirector() {
return managingDirector;
}
public void setManagingDirector(Employee managingDirector) {
this.managingDirector = managingDirector;
}
}
/**
* @Title: BeanWrapperTest.java
* @Package com.oscar999.valid
* @Description: TODO
* @author oscar999
* @date Sep 3, 2018 4:27:45 PM
* @version V1.0
*/
package com.oscar999.valid;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
/**
* @ClassName: BeanWrapperTest
* @Description: TODO
* @author oscar999
*/
public class BeanWrapperTest {
/**
* @Title: main
* @Description: TODO
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BeanWrapper company = new BeanWrapperImpl(new Company());
company.setPropertyValue("name","oscar999 Company Inc.");
//can also be done like this
/*PropertyValue value = new PropertyValue("name", "Some Company Inc.");
company.setPropertyValue(value);*/
BeanWrapper jim = new BeanWrapperImpl(new Employee());
jim.setPropertyValue("name", "Oscar999");
jim.setPropertyValue("salary", 1000000);
company.setPropertyValue("managingDirector", jim.getWrappedInstance());
Float salary = (Float) company.getPropertyValue("managingDirector.salary");
System.out.println("salary="+salary);
}
}
3.4.2 内置的PropertyEditor 实现
-使用PropertyEditor设置bean的属性
- 在MVC框架中解析Http请求参数
Class
Explanation
ByteArrayPropertyEditor
Editor for byte arrays. Strings will simply be converted to their corresponding byte representations. Registered by default by BeanWrapperImpl.
ClassEditor
Parses Strings representing classes to actual classes and the other way around. When a class is not found, an IllegalArgumentException is thrown. Registered by default by BeanWrapperImpl.
CustomBooleanEditor
Customizable property editor for Boolean properties. Registered by default by BeanWrapperImpl, but, can be overridden by registering custom instance of it as custom editor.
CustomCollectionEditor
Property editor for Collections, converting any source Collection to a given target Collection type.
CustomDateEditor
Customizable property editor for java.util.Date, supporting a custom DateFormat. NOT registered by default. Must be user registered as needed with appropriate format.
CustomNumberEditor
Customizable property editor for any Number subclass like Integer, Long, Float, Double. Registered by default by BeanWrapperImpl, but can be overridden by registering custom instance of it as a custom editor.
FileEditor
Capable of resolving Strings to java.io.File objects. Registered by default by BeanWrapperImpl.
InputStreamEditor
One-way property editor, capable of taking a text string and producing (via an intermediate ResourceEditor and Resource) an InputStream, so InputStream properties may be directly set as Strings. Note that the default usage will not close the InputStream for you! Registered by default by BeanWrapperImpl.
LocaleEditor
Capable of resolving Strings to Locale objects and vice versa (the String format is [country][variant], which is the same thing the toString() method of Locale provides). Registered by default by BeanWrapperImpl.
PatternEditor
Capable of resolving Strings to java.util.regex.Patternobjects and vice versa.
PropertiesEditor
Capable of converting Strings (formatted using the format as defined in the javadocs of the java.util.Propertiesclass) to Properties objects. Registered by default by BeanWrapperImpl.
StringTrimmerEditor
Property editor that trims Strings. Optionally allows transforming an empty string into a null value. NOT registered by default; must be user registered as needed.
URLEditor
Capable of resolving a String representation of a URL to an actual URL object. Registered by default by BeanWrapperImpl.
3.5 Spring类型转换
继承Convert接口
/**
* @Title: StringToInteger.java
* @Package com.oscar999.valid
* @Description: TODO
* @author oscar999
* @date Sep 3, 2018 4:47:22 PM
* @version V1.0
*/
package com.oscar999.valid;
import org.springframework.core.convert.converter.Converter;
/**
* @ClassName: StringToInteger
* @Description: TODO
* @author oscar999
*/
public class StringToInteger implements Converter<String, Integer> {
@Override
public Integer convert(String source) {
return Integer.valueOf(source);
}
}
3.5.2 ConverterFactory
当需要集中转换整个类层级逻辑时,例如: 转换Stirng 到枚举java.lang.Enum, 继承ConverterFactory
/**
* @Title: StringToEnumConverterFactory.java
* @Package com.oscar999.valid
* @Description: TODO
* @author oscar999
* @date Sep 3, 2018 4:51:27 PM
* @version V1.0
*/
package com.oscar999.valid;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
/**
* @ClassName: StringToEnumConverterFactory
* @Description: TODO
* @author oscar999
* @param <S>
*/
public class StringToEnumConverterFactory<S> implements ConverterFactory<String,Enum> {
@Override
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToEnumConverter(targetType);
}
private final class StringToEnumConverter<T extends Enum> implements Converter<String, T> {
private Class<T> enumType;
public StringToEnumConverter(Class<T> enumType) {
this.enumType = enumType;
}
public T convert(String source) {
return (T) Enum.valueOf(this.enumType, source.trim());
}
}
}
3.5.3 GenericConverter
需要复杂的转换实现时,考虑使用。
3.5.4 ConversionService API
ConversionService定义了统一的接口用于在运行时执行类型转换逻辑。转换器通常在此接口之后执行。
3.5.3 配置ConversionService
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean"/>
或者
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="example.MyCustomConverter"/>
</set>
</property>
</bean>
3.5.6 程式使用ConversionService
@Service
public class MyService {
@Autowired
public MyService(ConversionService conversionService) {
this.conversionService = conversionService;
}
public void doIt() {
this.conversionService.convert(...)
}
}
}
3.6 Spring 栏位格式
public class MyModel {
@NumberFormat(style=Style.CURRENCY)
private BigDecimal decimal;
}
}
public class MyModel {
@DateTimeFormat(iso=ISO.DATE)
private Date date;
}
}
3.8 Sprin 验证
public class PersonForm {
private String name;
private int age;
}
}
JSR-303标准
public class PersonForm {
@NotNull
@Size(max=64)
private String name;
@Min(0)
private int age;
}
}
配置Validator
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
Java 的
import javax.validation.Validator;
@Service
public class MyService {
@Autowired
private Validator validator;
Spring的:
import org.springframework.validation.Validator;
@Service
public class MyService {
@Autowired
private Validator validator;
}
}
3.8.3 配置DataBinder
DataBinder可以配置一个Validator, 当调用binder.validate()会触发验证。
- 空白目录
- 0.环境准备
- 0.1基于maven的工程创建
- 1.控制反转容器
- 1.1 Spring控制反转容器和beans介绍
- 1.2 容器概览
- 1.3 Bean概览
- 1.4 依赖
- 1.5 Bean的范围
- 1.6 客制bean的特性
- 1.7 Bean定义的继承
- 1.8 容器扩展点
- 1.9 基于注解的容器配置
- 1.10 类路径扫描及组件管理
- 1.11 使用JSR 330标准的注解
- 1.12 基于Java的容器配置
- 1.12.1 基本概念: @Bean 和 @Configuration
- 1.13 环境抽象化
- 1.14 注册一个LoadTimeWeaver
- 1.15 ApplicationContext的附加功能
- 1.16 BeanFactory
- 2. 资源
- 3. 验证,数据绑定和类型转换
- 4. Spring表达式语言(SpEL)
- 5. Spring面向方面的切面编程
- 6. Spring AOP 接口
- 7. 空安全
- 8. 数据缓冲和编码
- 9. 附录