Common Validation Framework - How To Validate a Java Bean
Recently, more and more java developers show the great interesting on validation of java objects. This article (The importance of Being Valid) describes the importance of being valid. Several years ago, there maybe only presentation-layer validation, such as Struts Validation Framework. After that, Apache abstracts Apache Common Validation Framework from struts validation. Unfortunately, this common validation is still tightly connected to presentation-layer.
Now, lots of new framework is coming. The following is the uncompleted list of java validation framework
And JSR 303 (Bean Validation) try to come out a set of standards of bean validation and now is on Early Draft Review stage. However, i didn’t find any implementation already supporting this spec.
After some investigation, i selected Spring Bean Validation Module. The major reasons are
Unfortunately, there are very few examples to show how to use Spring framework without Spring MVC framework. This one is the only reference – Annotation-Based Validation with the Spring Bean Validation Framework.
This article describes how to use Spring Bean Framework in your code.
public class AuthenticateUserInput extends Input {
@NotNull(errorCode = UserAccountErrorCodeAndMessage.AUTHENTICATE_USER_INPUT_ACCOUNT_NAME_IS_NULL,
@NotBlank(errorCode = UserAccountErrorCodeAndMessage.AUTHENTICATE_USER_INPUT_ACCOUNT_NAME_IS_EMPTY,message="account name cannot be blank")
private String accountName;
@NotNull(errorCode = UserAccountErrorCodeAndMessage.AUTHENTICATE_USER_INPUT_ACCOUNT_NAME_IS_NULL,message="user name cannot be null")
@NotBlank(errorCode = UserAccountErrorCodeAndMessage.AUTHENTICATE_USER_INPUT_ACCOUNT_NAME_IS_EMPTY,message="user name cannot be blank")
private String userName;
@NotNull(errorCode = UserAccountErrorCodeAndMessage.AUTHENTICATE_USER_INPUT_PASSWORD_IS_NULL,message="password cannot be null")
@NotBlank(errorCode = UserAccountErrorCodeAndMessage.AUTHENTICATE_USER_INPUT_PASSWORD_IS_EMPTY,message="password cannot be blank")
private String password;
// getter and setter for attributes
}
In the above example, each attribute has two annotation based validation rules - (1) NotNull: its error code is a user-defined string, and the message will be returned if specified (2) NotBlank: its error code is a user-defined string, and the message will be returned if specified <beans default-autowire="byName" xsi:schemalocation="
<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a>
<a href="http://www.springframework.org/schema/beans/spring-beans.xsd">http://www.springframework.org/schema/beans/spring-beans.xsd</a>
<a href="http://www.springmodules.org/validation/bean/validator">http://www.springmodules.org/validation/bean/validator</a>
<a href="http://www.springmodules.org/validation/bean/validator.xsd">http://www.springmodules.org/validation/bean/validator.xsd</a>"
xmlns:vld="http://www.springmodules.org/validation/bean/validator"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">
<!--Bean Validator-->
<vld:annotation-based-validator id="beanValidator">
<!--vld:xml-based-validator id="validator">
<vld:resource location="classpath:validation.xml"/>
</vld:xml-based-validator-->
<!--bean id="configurationLoader" class="org.springmodules.validation.bean.conf.loader.xml.DefaultXmlBeanValidationConfigurationLoader">
<property name="resource" value="classpath:validation.xml"/>
</bean>
<bean id="beanValidator" class="org.springmodules.validation.bean.BeanValidator">
<property name="configurationLoader">
<ref bean="configurationLoader"/>
</property>
</bean-->
</vld:annotation-based-validator></beans>
public
class
CommonValidator {
private
static
CommonValidator instance
=
createInstance();
private
Validator validator;
/**
* This is a singleton class.
*/
private
CommonValidator() { }
private
static
CommonValidator createInstance() {
return
new
CommonValidator(); }
public
static
CommonValidator getInstance() {
return
instance; }
/**
*
@return
the validator
*/
public
Validator getValidator() {
return
validator; }
/**
*
@param
validator the validator to set
*/
public
void
setValidator(Validator validator) {
this
.validator
=
validator; }
public
boolean
validate(Input input, Output output) { Errors errors
=
new
BindException(input,
""
); validator.validate(input, errors);
if
(errors.hasErrors()) {
for
(Object o : errors.getAllErrors()) { FieldError e
=
(FieldError)o; String errorCode
=
e.getCode(); errorCode
=
errorCode.substring(errorCode.indexOf(
'
[
'
)
+
1
, errorCode.indexOf(
'
]
'
)); output.addError(errorCode, e.getDefaultMessage()); }
return
false
; }
return
true
; } }
So, the spring framework will inject user-defined validator instance into this class with initialization time. And boolean validate(Input, Output) is the only method to validate a input. If any validation rule is violated, the output class get add a error. The last step will show the configuration to inject user-defined validator. It is also in AppContext.xml.
<bean class="com.starcite.user.validator.CommonValidator" id="commonValidator" factory-method="getInstance">
<property name="validator">
<ref bean="beanValidator">
</ref></property>
</bean>
Have Fun!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.