在XML

2012-10-16 64 views
4

這裏的規則驗證的Java對象是我的問題的一個例子:在XML

1)我在那裏的規則我的發票是definded

<rules> 
.. 
    <price> 
    <Required>True</Required> 
    <MinValue>0.1</MinValue> 
    <price> 
.. 
</rules> 

2的XML文件)我有一個發票對象在Java(重要:本應保持如此(平原)沒有說明或任何應包括在內。)

public class Invoice implements Serializable { 

    private String details; 
    private String tax; 
    private String recipient; 
    private double price; 

    //getter and setter 

}

3)和至少我有一個驗證器對象

public class Validator(){ 

    public boolean validate(String xmlfile, Invoice i) { 
      //todo: Invoice i should be validated with xmlfile 
    } 
} 

我需要什麼: 確認者應採取的XML文件的規則內 例如

<price> 
    <Required>True</Required> 
    <MinValue>0.1</MinValue> 
    <price> 

並使用該規則驗證發票java對象。

有沒有什麼好的框架,我可以用它呢?或教程?途徑? 任何幫助真的很感激。

謝謝。

+1

我會使用屬性而不是文本,例如, Adam

+1

也許bean驗證? http://beanvalidation.org/1.0/spec/ – rolve

回答

2

您可以使用Hibernate Validator這是實現JSR 303的你可以寫在XML約束如下

<field name="x2" ignore-annotations="true" > <!-- XML is stronger --> 
     <constraint annotation="javax.validation.constraints.Min"> 
      <element name="value">2</element> 
     </constraint> 
    </field> 

一個完整的和漂亮的教程可以發現here

+0

這不太好。 xml文件應儘可能簡單,以便公司可以在其中添加規則。例如需要不需要

+1

我會說在你的XML中添加一個包裝來轉換爲這個XML。編寫你的實現將實現你的一點 –

+0

我想你可以去那裏。由於您不需要註釋和簡單的XML –

0

對於此用例,我將使用Bean驗證(JSR 303的實現。驗證規則可以被定義爲一個XML文檔。

Hibernate驗證器的參考實現,它可以在這裏下載:

JSR 303的實現也將被包含在所有的Java EE 6實現。

+0

嗨。你有沒有例子或參考?或者是一個教程,文檔是在哪裏完成的?會很好,謝謝 –

+0

@ Delta458 - 以下可能有所幫助:http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-xmlconfiguration.html –

1

對從這個例子來看看Apache的。

public class ValidateExample extends Object { 

    /** 
     * We need a resource bundle to get our field names and errors messages 
     * from. Note that this is not strictly required to make the Validator 
     * work, but is a good coding practice. 
     */ 
     private static ResourceBundle apps = 
      ResourceBundle.getBundle(
       "org.apache.commons.validator.example.applicationResources"); 

     /** 
     * This is the main method that will be called to initialize the Validator, create some sample beans, and 
     * run the Validator against them. 
     */ 
    public static void main(String[] args) 
     throws ValidatorException, IOException, SAXException { 

      InputStream in = null; 
      ValidatorResources resources = null; 

      try { 

       // Create a new instance of a ValidatorResource, then get a stream 
       // handle on the XML file with the actions in it, and initialize the 
       // resources from it. This would normally be done by a servlet 
       // run during JSP initialization or some other application-startup 
       // routine. 
       in = ValidateExample.class.getResourceAsStream("validator-example.xml"); 
       resources = new ValidatorResources(in); 

      } finally { 
       // Make sure we close the input stream. 
       if (in != null) { 
        in.close(); 
      } 
      } 

     // Create a test bean to validate against. 
     ValidateBean bean = new ValidateBean(); 

      // Create a validator with the ValidateBean actions for the bean 
      // we're interested in. 
      Validator validator = new Validator(resources, "ValidateBean"); 

      // Tell the validator which bean to validate against. 
      validator.setParameter(Validator.BEAN_PARAM, bean); 

      ValidatorResults results = null; 

      // Run the validation actions against the bean. Since all of the properties 
     // are null, we expect them all to error out except for street2, which has 
     // no validations (it's an optional property) 

     results = validator.validate(); 
     printResults(bean, results, resources); 

     // Now set all the required properties, but make the age a non-integer. 
     // You'll notice that age will pass the required test, but fail the int 
     // test. 
     bean.setLastName("Tester"); 
     bean.setFirstName("John"); 
     bean.setStreet1("1 Test Street"); 

     bean.setCity("Testville"); 

     bean.setState("TE"); 
     bean.setPostalCode("12345"); 
     bean.setAge("Too Old"); 
     results = validator.validate(); 
     printResults(bean, results, resources); 

     // Now only report failed fields 
     validator.setOnlyReturnErrors(true); 
     results = validator.validate(); 
     printResults(bean, results, resources); 

     // Now everything should pass. 
     validator.setOnlyReturnErrors(false); 
     bean.setAge("123"); 
     results = validator.validate(); 
     printResults(bean, results, resources); 
    } 

    /** 
     * Dumps out the Bean in question and the results of validating it. 
     */ 
    public static void printResults(
     ValidateBean bean, 
     ValidatorResults results, 
     ValidatorResources resources) { 

     boolean success = true; 

     // Start by getting the form for the current locale and Bean. 
     Form form = resources.getForm(Locale.getDefault(), "ValidateBean"); 

     System.out.println("\n\nValidating:"); 
     System.out.println(bean); 

     // Iterate over each of the properties of the Bean which had messages. 
     Iterator propertyNames = results.getPropertyNames().iterator(); 
     while (propertyNames.hasNext()) { 
      String propertyName = (String) propertyNames.next(); 

      // Get the Field associated with that property in the Form 
      Field field = form.getField(propertyName); 

      // Look up the formatted name of the field from the Field arg0 
      String prettyFieldName = apps.getString(field.getArg(0).getKey()); 

      // Get the result of validating the property. 
      ValidatorResult result = results.getValidatorResult(propertyName); 

      // Get all the actions run against the property, and iterate over their names. 
      Map actionMap = result.getActionMap(); 
      Iterator keys = actionMap.keySet().iterator(); 
      while (keys.hasNext()) { 
       String actName = (String) keys.next(); 

       // Get the Action for that name. 
       ValidatorAction action = resources.getValidatorAction(actName); 

       // If the result is valid, print PASSED, otherwise print FAILED 
       System.out.println(
        propertyName 
         + "[" 
         + actName 
         + "] (" 
         + (result.isValid(actName) ? "PASSED" : "FAILED") 
         + ")"); 

       //If the result failed, format the Action's message against the formatted field name 
       if (!result.isValid(actName)) { 
        success = false; 
        String message = apps.getString(action.getMsg()); 
        Object[] args = { prettyFieldName }; 
        System.out.println(
         "  Error message will be: " 
          + MessageFormat.format(message, args)); 

       } 
      } 
     } 
     if (success) { 
      System.out.println("FORM VALIDATION PASSED"); 
     } else { 
      System.out.println("FORM VALIDATION FAILED"); 
     } 

    } 

} 
+0

這是什麼樣的apache技術?你有參考嗎? –

+0

我想我找到了我在找的東西:http://commons.apache.org/validator/apidocs/org/apache/commons/validator/package-summary.html#doc.Usage.validator –