开发者

Is there a reasonable way to leverage Spring binding when my model can be represented by a simple type, rather than a custom bean?

Spring binding works nicely when your model is complex enough to warrant a custom domain object, but sometimes the application needs only to receive a simple piece of data from the user that doesn't really warrant a domain object. However, there doesn't seem to be any way to handle this case.

For example, we have a form where the user is prompted for an activation code, and nothing more. This can easily be represented by a String. On another page, we're asking the user to acce开发者_运维技巧pt an agreement, and indicate acceptance by checking a checkbox, then submitting the form. This is easily represented by a Boolean.

Unfortunately, I haven't found any way to bind these simple types and still retain the value-add that Spring brings to the table. In this case, I specifically want to use its validation, and expose validation errors to the user via a <form:error> tag. I end up writing a mostly-pointless class like the following:

public class VerificationBean {
    private String pin;

    public String getPin() {
        return pin;
    }

    public void setPin(String pin) {
        this.pin = pin;
    }
}

I toyed with the idea of just using regular <input> tags and pulling the user's input into my handler method with a @RequestParam annotation, which works well enough, but handling validation then becomes hairy because you're not provided a BindingResult or a Model to work with, and the idea of associating errors via <form:error> goes out the window. So, it seems less of a compromise to create a simple container class and use the well-understood Spring mechanisms than it does to do something custom, but I can't help but feel that this can't be that uncommon a scenario that there ought to be a better way to handle it than littering class hierarchies with beans that exist only for data binding purposes. It's not an awful transgression, but you know what purists we can be.

Has anyone else encountered a similar scenario and felt similarly? If so, what did you end up doing? We're using Spring 3.0.x here. Thanks.


I've used Spring MVC for ~5 years now and have run into this a number of times. I have not found a solution that I am happy with (so I guess I'm in the same boat as you).

My "solution" in the end was to move to Scala. Scala makes it much less of a pain to create these lame little form classes

class LameFormInput(@BeanProperty var pin: String = null)

And I can put as many of these class definitions as I want in a single file. I've found this to be a surprisingly big reason I love Scala.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜