开发者

How can I set a value after data binding, but before validation, in Spring MVC 3?

开发者 https://www.devze.com 2023-03-27 18:05 出处:网络
I need to set a \"time submitted\" field on one of my domain objects. Validation rules require that p开发者_开发技巧roperty to be there, but I can\'t have it set by data binding from the form because

I need to set a "time submitted" field on one of my domain objects. Validation rules require that p开发者_开发技巧roperty to be there, but I can't have it set by data binding from the form because then the user could change it. How can I set a property of the bound object (or about-to-be-bound object) before validation occurs?


I don't know if I understood your question correctly, but you have 2 options to manipulate your data, on client side using Java Script, on server side using customer Validator.

public class PersonValidator implements Validator {

    /**
    * This Validator validates just Person instances
    */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        Person p = (Person) obj;
        p.setanyValue(some value); //changing object value
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

Hope it helps.


Maybe Stuff

I believe that binding starts by creating a new instance of a class. Assuming that this is true, you could add a blah = new Date(); in the constructor. Although this would happen before binding, I believe it fulfills the core requirement of get the submit time, but don't let the client edit it.

If this is wrong, check out the InitializingBean interface (or the corresponding init-method bean attribute).

Looks like spring 3.0 has even more lifecycle options. check out section 3.6.1.4 Combining lifecycle mechanisms in the Spring 3.0 Reference.

Better Info

You should be able to register a handler interceptor and set the submit time therein.

Check out the 15.4.1 Intercepting requests - the HandlerInterceptor interface section in the Spring 3.0 Reference (link is above).

0

精彩评论

暂无评论...
验证码 换一张
取 消