如何验证操作方法中的空字段?
我有一个输入字段和一个按钮。我想在执行按钮操作之前检查 textinput
是否有效。如果有效,我将呈现一条响应消息。我有这样的代码:
public void submitReportRequest() {
if(nameField!=null){
System.out.println("aaaaaaaaaaaaa");
submitted=true;
}
if(nameField == null){
System.out.println("report name is null!!!!!!");
}
}
但从控制台我刚刚得到:
[#|2011-11-18T15:22:49.931+0200|INFO|glassfishv3.0|null|_ThreadID=21;_ThreadName=Thread-1;|aaaaaaaaaaaaa|#]
当 nameField
为空时,我在控制台中接收不到任何内容,只是使用 nameField< 的验证消息重新渲染页面/代码>。我从 JSF 生命周期知道,如果验证阶段失败,那么它会直接跳转到渲染响应阶段,并且永远不会达到按钮操作。但在这种情况下我怎样才能实现我的目标呢?
I have an input field and a button. I want to check if the textinput
is valid before executing the button action. If it is valid I will render a response message. I have a code like this:
public void submitReportRequest() {
if(nameField!=null){
System.out.println("aaaaaaaaaaaaa");
submitted=true;
}
if(nameField == null){
System.out.println("report name is null!!!!!!");
}
}
but from the console I just get:
[#|2011-11-18T15:22:49.931+0200|INFO|glassfishv3.0|null|_ThreadID=21;_ThreadName=Thread-1;|aaaaaaaaaaaaa|#]
when the nameField
is empty, I receive nothing in the console just page is re-rendered with the validation message of nameField
. I know from the JSF life cycle if the validation phase fails then it jumps directly to the render response phase and button action is never reached. But how can I achieve my objective in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
提交的空值默认为空字符串,而不是
null
。相反,您需要通过String#isEmpty()
:您可能还想覆盖空格。在这种情况下,请添加
trim()
:请注意,
String#isEmpty()
是在 Java 1.6 中引入的。如果由于某种原因您仍然使用 Java 1.5 或更早版本,那么您需要检查String#length()
代替。但是,这不是所需字段验证的正常方式。您应该将
required="true"
属性放在输入字段上。这样,JSF 将自行验证它并显示适当的消息,并跳过操作方法调用。
另请参阅:
Empty submitted values default to empty strings, not
null
. Instead, you need to check if the string is empty byString#isEmpty()
:You perhaps want to cover blank spaces as well. In that case, add
trim()
:Note that the
String#isEmpty()
is introduced in Java 1.6. If you're still on Java 1.5 or older for some reason, then you need to checkString#length()
instead.However, that's not the normal way of required field validation. You should put the
required="true"
attribute on the input field instead.This way JSF will validate it by itself and display the appropriate message and will skip the action method invocation.
See also: