parameter validation with net.sf.oval (in play framework)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-22 17:05:43

问题


I would love to use the @NotNull annotation (or @Required or anything) for my own methods. While this works quite well in Controller and Model classes I cant get it to work in my own. This probably is more of a net.sf.oval question then play framework. But it might be connected, I don't know.

I have a class like:

@net.sf.oval.guard.Guarded
public class SimulatorWrapper {

    public SimulatorWrapper setRedCode(@play.data.validation.Required @net.sf.oval.constraint.NotNull final String redCode) {
        // just gessing here:
        if(Validation.hasErrors()) throw new RuntimeException("invalid argument");
        if(redCode == null) throw new RuntimeException("null");
        // do stuff
        return this;
    }
}

When I call this method with a null parameter the if throws my exception, but @NotNull and @Required seem to do nothing at all. What am I doing wrong? The play framework project came with oval 1.5, I downloaded 1.8 and added it to the classpath in eclipse just in case the old one had problems.

I'm starting the server with "play test my-server" and then I navigate to my website (not a test yet, just simple site) with my browser.

Thanks, Alex

P.S. I know the "null is evil" discussion, but I dont have access to the rest of the code so I cant change that.


回答1:


The validation class is invoked to check the validation annotations by the Play framework only when a controller action is called.

Since you're not in a controller, the Validation on annotation won't be executed and the Required annotion won't be in Validation.hasErrors()

Instead of using annotation, you could use methods like: Validation.required(redCode); //It'll check for null And after that, call Validation.hasErrors() and it should work.

However, I don't think you should do this because the errors from Validation.hasError() should come from Validation on the controller action invocation and it can cause you side effects.

If you want to do something like your example, you should not rely on the play Validation class.

Are you sure you're using validation at the right places ?




回答2:


In case anyone still needs this.

You can do validation with Play annotations in all classes exactly the same way as in controllers. Just use validate plugin.



来源:https://stackoverflow.com/questions/8562353/parameter-validation-with-net-sf-oval-in-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!