日期:2014-05-19 浏览次数:20948 次
  // Java example to validate required fields
  public Class Validator {
      ...
      public static boolean validateRequired(String value) {
          boolean isFieldValid = false;
          if (value != null && value.trim().length() > 0) {
              isFieldValid = true;
          }
          return isFieldValid;
      }
      ...
  }
  ...
  String fieldValue = request.getParameter("fieldName");
  if (Validator.validateRequired(f ieldValue)) {
      // fieldValue is valid, continue processing request
      ...
  }  // Java example to validate that a f ield is an int number
  public Class Validator {
      ...
      public static boolean validateInt(String value) {
          boolean isFieldValid = false;
          try {
              Integer.parseInt(value);
              isFieldValid = true;
          } catch (Exception e) {
              isFieldValid = false;
          }
          return isFieldValid;
      }
      ...
  }
  ...
  // check if the HTTP request parameter is of type int
  String f ieldValue = request.getParameter("f ieldName");
  if (Validator.validateInt(f ieldValue)) {
      // f ieldValue is valid, continue processing request
      ...
  }  // Example to convert the HTTP request parameter to a primitive wrapper data type
  // and store this value in a request attribute for further processing
  String f ieldValue = request.getParameter("f ieldName");
  if (Validator.validateInt(f ieldValue)) {
      // convert f ieldValue to an Integer
      Integer integerValue = Integer.getInteger(f ieldValue);
    // store integerValue in a request attribute
      request.setAttribute("f ieldName", integerValue);
  }
  ...
  / / Use the request attribute for further processing
  Integer integerValue = (Integer)request.getAttribute("f ieldName");
  ...  // Example to validate the f ield length
  public Class Validator {
      ...
      public static boolean validateLength(String value, int minLength, int maxLength) {
          String validatedValue = value;
          if (!validateRequired(value)) {
              validatedValue = "";
          }
          return (validatedValue.length() >= minLength &&
                      validatedValue.length() <= maxLength);
      }
      ...
  }
  ...
  String userName = request.getParameter("userName");
  if (Validator.validateRequired(userName)) {
      if (Validator.validateLength(userName, 8, 20)) {
          / / userName is valid, continue further processing
          ...
      }
  }  / / Example to validate the f ield range
  public Class Validator {
      ...
      public static boolean validateRange(int value, int min, int max) {
          return (value >= min && value <= max);
      }
      ...
  }
  ...
  String f ieldValue =