Spring MVC 中的可配置验证



我正在使用带有注释的Spring验证机制。验证必须在 messages_en.properties 中可配置。为此,提供此文件中的条目password.min=4

如何根据 bean 中的设置配置@Size messageSource验证器?

public class SubmitModel {
@Size(min = "#{new Integer(messageSource[login.ok])}") //does not work. @Size expects integer value
private String password;
}

Bean 配置:

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>langmessages</value>
    </property>
</bean>

我已经尝试配置静态常量,但这里再次需要一个常量表达式。仅供参考,需要此机制来验证控制器中的传入请求:

@RequestMapping (value = "/device/{devicename}", method = RequestMethod.GET, produces="text/xml")
@ResponseBody
public String handleRequest(@PathVariable("devicename") String devicename, @Valid @ModelAttribute SubmitModel model, BindingResult errors) throws UCLoginException { ... }

密码长度必须超过login.ok值的典型示例:http://my.domain.com:8080/submit/device/SPAxxxxx?name=adam&password=454321

是不可能的。注释属性的值必须是常量,并且在编译后不能更改。如果需要该级别的可自定义配置,请使用自定义Validator

@Inject
private SubmitModelValidator customValidator;
public String handleRequest(@PathVariable("devicename") String devicename, @Valid @ModelAttribute SubmitModel model, BindingResult errors) throws UCLoginException { ... }
    customValidator.validate(model, errors);
    if (errors.hasErrors()) {
        ...
    }
    ...
}

其中SubmitModelValidator是一个Validator实现,您已经为其创建了一个 bean 并使用 @Value 从属性设置了各种字段。

最新更新