爲了在網頁上顯示某些內容,您需要使用該API調用Drools並獲取一些輸出,然後可以通過Web應用程序呈現該輸出。
因此,您需要考慮如何從Java代碼中獲取輸出。有幾種方法可以做到這一點。
例如,在執行諸如驗證請求等簡單操作時,只需對插入的請求進行操作即可。例如:
rule "IBAN doesn't begin with a country ISO code."
no-loop
when
$req: IbanValidationRequest($iban:iban, $country:iban.substring(0, 2))
not Country(isoCode == $country) from countryList
then
$req.reject("The IBAN does not begin with a 2-character country code. '" + $country + "' is not a country.");
update($req);
end
在那個例子中,我對我插入的事實調用了一個「拒絕」方法。這會修改插入的事實,以便在規則執行後,我的Java代碼中有一個對象,並帶有一個標誌來指示它是否被拒絕。此方法適用於無狀態知識會話。即
- Java代碼 - 通過API插入要求其實
- Drools的規則 - 修改請求的事實(標誌排斥,註釋,設置屬性等)
- Java代碼 - 看看事實,看看是什麼做它
如何進行這種互動是從以下全colass採取下面的代碼示例:
https://github.com/gratiartis/sctrcd-payment-validation-web/blob/master/src/main/java/com/sctrcd/payments/validation/payment/RuleBasedPaymentValidator.java
// Create a new knowledge session from an existing knowledge base
StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
// Create a validation request
PaymentValidationRequest request = new PaymentValidationRequest(payment);
// A stateless session is executed with a collection of Objects, so we
// create that collection containing just our request.
List<Object> facts = new ArrayList<Object>();
facts.add(request);
// And execute the session with that request
ksession.execute(facts);
// At this point, rules such as that above should have been activated.
// The rules modify the original request fact, setting a flag to indicate
// whether it is valid and adding annotations to indicate if/why not.
// They may have added annotations to the request, which we can now read.
FxPaymentValidationResult result = new FxPaymentValidationResult();
// Get the annotations that were added to the request by the rules.
result.addAnnotations(request.getAnnotations());
return result;
有狀態會話中的另一種選擇是規則可以將事實插入工作內存。執行規則後,您可以通過API查詢會話並檢索一個或多個結果對象。您可以使用KnowledgeSession的getObjects()方法獲取會話中的所有事實。爲了獲得具有特定屬性的事實,還有一個getObjects(ObjectFilter)方法。下面鏈接的項目提供了在KnowledgeEnvironment和DroolsUtil類中使用這些方法的示例。
或者,您可以將服務作爲全局變量插入。規則可以調用該服務的方法。
有關如何在Web應用程序中使用Drools的示例,我最近打開了此Web站點,它提供了一個REST API來調用Drools規則並獲取響應。
https://github.com/gratiartis/sctrcd-payment-validation-web
如果你已經安裝了Maven的時候,你應該可以嘗試一下很快,和玩的代碼。
我有一個關於你給我的鏈接問題。我沒有在我的項目中設置任何'pom.xml',因爲我不知道它是什麼以及它是否有必要。還有關於您發佈的選項3,我將如何使用Java代碼查看事實?對不起,一個真正的noob問題。 – user2785929
pom.xml定義了項目的依賴關係。它由Maven使用,Maven使用它來確定要下載哪些jar並將其捆綁到web項目中。 – Steve
針對如何查詢會話事實的答案增加了一些額外的細節。 – Steve