我将此Java Server Faces验证程序用于配置文件编辑表单。但我遇到了这个问题。例如,我有ID为45的帐户。如果我提交表单,我将收到此ID已存在的错误。
public void validateAccountID(FacesContext context, UIComponent component, Object value) throws SQLException
{
Long l;
String s = value.toString().trim();
if (s.length() > 18)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Value is too long! (18 digits max)", null));
}
try
{
l = Long.parseLong(s);
if (l > Integer.MAX_VALUE)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + l + "' is too large!", null));
}
}
catch (NumberFormatException nfe)
{
l = null;
}
if (l != null)
{
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
int cnt = 0;
try
{
conn = ds.getConnection();
ps = conn.prepareStatement("SELECT count(1) from ACCOUNT where ID = ?");
ps.setLong(1, l);
rs = ps.executeQuery();
while (rs.next())
{
cnt = rs.getInt(1);
}
if (cnt > 0)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + l + "' is already in use!", null));
}
}
catch (SQLException x)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" SQL error!", null));
}
finally
{
if (ps != null)
{
ps.close();
}
if (conn != null)
{
conn.close();
}
}
}
else
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
s.isEmpty() ? " This field cannot be empty!" : " '" + s + "' is not a number!", null));
}
}
当我点击提交以允许他自己的ID成功编辑帐户时,当我打开帐户45的帐户个人资料页面时,我需要实现一些逻辑。你能提出一些sotlution吗?
答案 0 :(得分:-1)
在编辑表单中,当发现数据库中存在此ID时,不应抛出异常。这是现有帐户的预期 - 在数据库中有记录。您的验证应该是用户在登录时访问编辑表单。他记录了你在用户Bean上设置了一些标记为已记录,这里只是检查用户是否仍然登录以便在他自己的配置文件上进行更改。 1登录时 - 检查用户是否存在于数据库中,并且提供的密码是否正确; - 将UserBean中记录的布尔标志设置为true 2.在子目录编辑表单上: - 检查用户是否仍然记录并验证表格的其余字段