我在JSF验证器中获得NPE,但我找不到导致此问题的原因:
// Validate Datacenter Name
public void validateDatacenterName(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
{
// Original value
Object modelValue = ((UIInput) component).getValue();
String oriDCName = modelValue.toString();
String s; // New inserted value
if (value != null && !(s = value.toString().trim()).isEmpty())
{
if (s.length() > 18)
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" Value is too long! (18 digits max)", null));
}
if (ds == null)
{
throw new SQLException("Can't get data source");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs;
String resDCName = null;
try
{
conn = ds.getConnection();
// if componentsstatsid <> edited componentstatsid in jsf -> throw validator exception
ps = conn.prepareStatement("SELECT NAME from COMPONENTSTATS where NAME = ?");
ps.setString(1, s);
rs = ps.executeQuery();
while (rs.next())
{
resDCName = rs.getString(1);
}
if (resDCName != null && (!resDCName.equals(oriDCName) ))
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + s + "' 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,
" This field cannot be empty!", null));
}
}
当我输入唯一的新值时,我得到NPE。当我输入已在DB表中找到的值时,我得到...is already in use!
。
问题出在if (resDCName != null && (!resDCName.equals(oriDCName) ))
,但我无法解决。知道如何解决这个问题吗?
答案 0 :(得分:1)
改变你的逻辑,如下面的代码。我假设你想resDCname不应该等于origDCName。
while (rs.next())
{
resDCName = rs.getString(1);
if (resDCName != null && resDCName.equals(oriDCName))
{
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
" '" + s + "' is already in use!", null));
}
}