1

我在 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。当我输入已经在数据库表中找到的值时,我得到...is already in use!.

问题出在某个地方,if (resDCName != null && (!resDCName.equals(oriDCName) ))但我无法解决。知道如何解决这个问题吗?

4

1 回答 1

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));
     }
   }
于 2013-02-05T11:27:51.237 回答