1

I'm new to Drools Expert, currently from the Sample project of the drools what I can only do is print something to the console. Now I integrate drools to a web project and It was successful, I was be able to print something to the console depending on the interaction of the user to the page.

My rules currently is like this:

rule "A test Rule"

    when
        m: FLTBean ( listeningScore == 1, test : listeningScore  )
    then
        System.out.println( test );

end

So what if I want to print it out to a web page? How would I do that? Do I need to use return to return some value back to the java page and render it to the page?

4

1 回答 1

1

为了在网页上显示某些内容,您需要使用 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 代码中有一个对象,带有一个标志来指示它是否被拒绝。此方法适用于无状态知识会话。IE

  1. Java 代码 - 通过 API 插入请求事实
  2. Drools 规则 - 修改请求事实(标志拒绝、注释、设置属性等)
  3. Java 代码 - 查看事实以了解对其做了什么

以下如何执行此交互的代码示例取自以下完整的 colas:

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 的示例,我最近打开了这个网站,它提供了一个 REST API 来调用 Drools 规则并获取响应。

https://github.com/gratiartis/sctrcd-payment-validation-web

如果您安装了 Maven,您应该能够很快地试用它,并使用代码。

于 2013-10-23T14:35:47.667 回答