0

我有一个自定义异常类,需要从属性文件中读取一些错误消息。但它似乎继续为空。我什至尝试添加 @Component 但仍然无法正常工作

@Component
public class FormValidationFailExceptionHolder {

    @Autowired
    private MessageSource messageSource;

    ...
    public void someMethod(){
        ....
        String message = messageSource.getMessage(errorid, msgargs, Locale.ENGLISH);
        ....
    }
}

这是我的弹簧配置

....
<context:component-scan base-package="simptex.my" />
....
 <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="useCodeAsDefaultMessage" value="false" />
    <property name="basenames">
        <list>
            <value>classpath:mgmtlabels</value>
            <value>classpath:error</value>
            <value>classpath:PWMResources</value>
        </list>
    </property>
    <property name="defaultEncoding" value="UTF-8" />
</bean>

我什至尝试在 spring config xml 中显式声明 bean,但仍然返回 null

<bean id="formValidationFailException" class="simptex.my.core.exception.FormValidationFailException">
    <property name="messageSource" ref="messageSource" />
</bean>

这是我如何调用 FormValidationFailException

public class Foo{
    private HttpSession session;
    ....
    public void fooMethod()  {
        session.setAttribute(CommonSessionKeys.FORM_VALIDATION_EXECEPTION_HOLDER, new FormValidationFailExceptionHolder("roledd", "E0001"));
    }
}

@Controller
public class FooController  {
    @RequestMapping(value = "/xxxx")
    public void fooMethodxxx() {
        Foo foo = new Foo(session);
        foo.fooMethod();
    }
}
4

1 回答 1

0

据我了解,您真正想要实现的是自定义表单验证器。

@Component
public class CustomValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return clazz == FormBean.class;
    }

    @Override
    public void validate(Object target, Errors errors) {
        FormBean bean = (FormBean) target;

        if ( StringUtils.isEmpty( bean.getField() ) ) {
            errors.rejectValue("field", "field.empty");
        }

    }
}

“field.empty”是属性文件中的一个键。

field.empty=Field mustn't be empty

现在在您的控制器中,您需要添加:

@Autowired
private CustomValidator customValidator; 

@InitBinder
protected void initBinder(WebDataBinder binder) {
    if (binder.getTarget() instanceof FormBean) {
        binder.setValidator(customValidator);
    }
}

@RequestMapping(value = "/xxxx", method = RequestMethod.POST)
    public String fooMethodxxx(@ModelAttribute("bean") @Validated FormBean bean, BindingResult result) {
        if ( result.hasErrors() ) {
            prepareModel(model);
            return "form.view";
        }
        return "other.view"
    }

当您发布表单时,它将被验证。要在 jsp 中向用户显示验证消息,您需要添加:

<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form"%>

<f:errors cssClass="error" path="field"></f:errors>
<f:input path="field" type="text"/>

我认为这是处理自定义验证器的正确方法。

于 2013-09-30T07:59:16.100 回答