有三個主要的設定,一是設定Validator instance,implementation可以使用Hibernate Validator;另一個是設定SpringValidationInterceptor和SpringI18nInterceptor,三者我們都交給Spring控管;最後在struts.xml中設定interceptor,並套用到Action就可以了。
Spring XML
<bean id="gmo.cao.validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
Spring Configuration
package com.gss.gmo.cao.struts2.spring;
import javax.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.gss.gmo.cao.struts2.interceptor.SpringI18nInterceptor;
import com.gss.gmo.cao.struts2.interceptor.SpringValidationInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;
@Configuration
public class InterceptorConfiguration {
final static String EXCLUDE_METHODS = "input, back, cancel, browse";
@Bean(name = "gmo.cao.springI18n")
Interceptor getSpringI18nInterceptor() {
return new SpringI18nInterceptor();
}
@Bean(name = "gmo.cao.springValidation")
@Autowired
Interceptor createSpringValidationInterceptor(@Qualifier("gmo.cao.validator") Validator validator) {
SpringValidationInterceptor interceptor = new SpringValidationInterceptor();
interceptor.setExcludeMethods(EXCLUDE_METHODS);
interceptor.setValidator(validator);
return interceptor;
}
}
import javax.validation.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.gss.gmo.cao.struts2.interceptor.SpringI18nInterceptor;
import com.gss.gmo.cao.struts2.interceptor.SpringValidationInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;
@Configuration
public class InterceptorConfiguration {
final static String EXCLUDE_METHODS = "input, back, cancel, browse";
@Bean(name = "gmo.cao.springI18n")
Interceptor getSpringI18nInterceptor() {
return new SpringI18nInterceptor();
}
@Bean(name = "gmo.cao.springValidation")
@Autowired
Interceptor createSpringValidationInterceptor(@Qualifier("gmo.cao.validator") Validator validator) {
SpringValidationInterceptor interceptor = new SpringValidationInterceptor();
interceptor.setExcludeMethods(EXCLUDE_METHODS);
interceptor.setValidator(validator);
return interceptor;
}
}
struts.xml
<interceptor name="springI18n" class="gmo.cao.springI18n" />
<interceptor name="springValidation" class="gmo.cao.springValidation" />
<interceptor name="springValidation" class="gmo.cao.springValidation" />