4.1.3. Using Middleware Services
In the previous section we considered the encapsulation of business logic in a managed bean of the client tier. Now we will go further and implement our logic in the most appropriate place: on the middle tier. By doing this, we will achieve the following goals:
-
Our business methods will be available for all types of clients including Polymer UI.
-
We will be able to use APIs available only on the middleware: EntityManager, transactions, etc.
In order to invoke a middleware business method from the client, you need to create a service. Studio can help you to scaffold the service stub:
-
Switch to the Middleware section and click New > Service.
-
Change the service interface name to
DiscountService
. The bean class and service names will be changed accordingly. Click OK or Apply. -
Click IDE and open the service interface in your IDE. Create a method and implement it in the service class.
See an example implementation in the demo application:
-
CustomerBrowse.java and CustomerEdit.java - screen controllers that invoke the service.
-
DiscountService.java - service interface.
-
DiscountServiceBean.java - service implementation.
-
DiscountCalculator.java - a managed bean of the middle tier which actually calculates discounts. Of course, a service can contain the business logic itself, but we will use this delegate to share logic with entity listeners and JMX beans (see next sections).
Please note that this bean is different from the one mentioned in the previous section: it is located in the core module and uses EntityManager for loading the amount of purchases from the database.
Let’s now make our business method accessible for external clients through the REST API:
-
Open the service editor in Studio and switch to the REST Methods tab.
-
Select the REST invocation allowed checkbox for the method.
Studio will create the rest-services.xml
file and write the method description into it. After restarting the application server you will be able to invoke your business method using HTTP requests. For example, the following GET request should work with our online demo server:
Please note that the demo application allows anonymous access. In the most real-world usage scenarios you need to authenticate prior to executing REST requests.