我已经制作了这个用于验证字符串插入表单字段的 Java 方法:
public void validateDatacenterName(FacesContext context, UIComponent component,
Object value) throws ValidatorException, SQLException {
String 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 (s != 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 COMPONENTSTATS where COMPONENTSTATSID = ?");
ps.setString(1, s);
rs = ps.executeQuery();
while(rs.next())
cnt = rs.getInt(1);
if (cnt > 0) {
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,
s.isEmpty() ? " This field cannot be empty!" : " '" + s + "' is not a valid name!", null));
}
}
如何改进此代码?为了改进表单验证器,我可以添加任何其他检查吗?
任何帮助将不胜感激!