Play框架:自动验证控制器方法是否适用? [英] Play Framework: automatic validation of controller methods applied?

查看:80
本文介绍了Play框架:自动验证控制器方法是否适用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对传递给控制器​​方法的参数的验证有些疑问.

I have some issue with validation of parameters passed to a controller method.

按照本教程的建议,我对实体的保存"和创建新"使用相同的控制器方法.参见示例 http://www.playframework.org/documentation/1.2.4/guide9

Following the suggestion from the tutorial, I am using the same controller method for "save" and "create new" of an entity. See example in http://www.playframework.org/documentation/1.2.4/guide9

所以,我的控制器方法如下:

So, my controller method looks like:

public static void saveEntity(long l, Long itemId,  
  @Required(message="error.shouldspecifyname") String name, 
  @Required(message="error.shouldspecifycategory")  String category)

如果"itemId"不是通过HTTP请求发送的数据的一部分,则应将其设置为"null".

If 'itemId' is not part of the data sent via an HTTP request - it is supposed to be set to 'null'.

不幸的是,似乎播放"是自动在丢失"参数上添加了验证错误.

Unfortunately, it seems like "Play" is automatically adding a validation error on the "missing" parameter.

当查看验证错误"列表时,每次"itemId"为"null"时-我在字段 itemId

When looking into the validation errors' list, every time 'itemId' is 'null' - I am getting an error Incorrect value for field itemId

这是有据可查的行为吗?用任何方法覆盖它,或摆脱"错误.

Is it a documented behavior? Any way to override it, or "get rid" of the error.

我只是使用重定向来处理错误,例如:

I am handling the errors simply using redirection, like:

if(validation.hasErrors() ) 
{

            validation.keep();
            showSomePage();         
}

因此,错误会在生成的上下文之外显示".这就是自动"错误困扰我的原因.

So the errors are displayed "out of the context" they get generated. This is the reason the "automatic" error bothers me.

感谢任何提示.

推荐答案

很可能由于声明为Long而无法验证itemId,您确定那里的蚂蚁不仅是long,而且是long.我们在每个地方都使用控制器进行验证,它与@Required一起使用,并将"null"传递给"Long"值.

Most likely it fails to validate itemId because it's declared as Long, are you sure you have "Long" there ant not just "long"? We are using validation with controllers every where and it works with @Required and passed "null" to "Long" values.

在最坏的情况下,您可以基于"itemId"键从验证对象中删除错误,同样,如果您使用控制器保存模型对象,则可能要使用:

Worst case you can remove error from validation object based on "itemId" key, also if you're using controller to save model object, you might want to use:

public static void saveEntity(@Required @Valid MyEntity entity) {
if(validation.hasErrors() ) {
  validation.keep();
  showSomePage();         
}
entity.save();
}

如果您通过以下方式从页面传递ID,则会自动将您所做的更改挂接到现有实体中:

It will automaticly hook your changes inside existing entity if you pass ID from page with:

<input type="hidden" name="myEntity.id" value="${myEntity.id}">

这篇关于Play框架:自动验证控制器方法是否适用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆