【发布时间】:2015-06-24 20:33:51
【问题描述】:
我想为输入字段创建验证器,以便检查值并在插入的值不是 int 时发送错误消息。
豆:
public class PricingCalculatorValidator implements Validator
{
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
// Cast the value of the entered input to String.
String input = (String) value;
// Check if they both are filled in.
if (input == null || input.isEmpty())
{
return; // Let required="true" do its job.
}
// Compare the input with the confirm input.
if (containsDigit(input))
{
throw new ValidatorException(new FacesMessage("Value is not number."));
}
}
public final boolean containsDigit(String s)
{
boolean containsDigit = false;
if (s != null && !s.isEmpty())
{
for (char c : s.toCharArray())
{
if (containsDigit = Character.isDigit(c))
{
break;
}
}
}
return containsDigit;
}
}
转换插入值的正确方法是什么?现在我得到异常
serverError: class java.lang.ClassCastException java.lang.Integer cannot be cast to java.lang.String
【问题讨论】:
-
我认为正确的方法是使用转换器。例如,您可以使用
f:convertNumber。 -
看起来你的 value 参数是
Integer类型的。在那种情况下String input = (String) value;这将不起作用。如果你想把它转换成String,你可以试试value.toString();。这将为您提供String代表Integer值。