特殊校驗不能加到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. 附錄