Introduction to XSJS Service

Introduction:

In the article Introduction to SAP HANA XS, we explained that SAP HANA XS can be used to expose data from Tables, Views and Modeling Views to UI layer.
In HANA XS, there are major 2 ways to expose data the data to clients – OData and XSJS.
In this article we will explain:
  • What is XSJS services in HANA?
  • How to create XSJS service with examples.
Note: For OData, read the article SAP HANA OData Service

What is SAP HANA XS JavaScript (XSJS)?

SAP HANA XS JavaScript (XSJS) is an application programming language in JavaScript. It can be used to exposes data stored in database tables or views to client side. Additionally we can also implement any business logic.

Unlike XSODATA, XSJS is a free flow approach where we can write our own logic using JavaScript.

Below is an example of XSJS service:


Create Hello World XSJS Service:

Let us create a simple XSJS service to understand the concept better.
We have also provided a list of XSJS examples for you. To know more about that, read the article SAP HANA XSJS Examples
Now let us see how to create an XSJS service.

Prerequisites:

Note: In this example we will use HANA Studio to create XSJS Service. You can also create it using HANA Web-based tools. For HANA Web-based tool, you should first read Create Your First HANA XS Application using HANA Web-Based Tool

Steps to create XSJS Service:

1. Create a XS project as mentioned in the article Create Your First HANA XS Application using HANA Studio
2. Right click on the project and select New à XS JavaScript File. Specify the name “HelloWorld” and click on Finish.



3. Copy and paste the below code.

$.response.contentType = "text/html";
var output = "Hello, " + $.session.getUsername() + " <br><br>";

var conn = $.db.getConnection();
var pstmt = conn.prepareStatement( "SELECT CURRENT_USER FROM DUMMY" );
var rs = pstmt.executeQuery();

if (!rs.next()) {
                $.response.setBody( "Failed to retrieve data" );
                $.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
else {
                output = output + "The current user is: " + rs.getString(1);
}
rs.close();
pstmt.close();
conn.close();
$.response.setBody(output);

Click here to download the source code. 
4. Right click and select Team à Activate. This will activate the file.


5. Right click and select Run As à XS Service. This will open the XSJS service in default browser.
6. Enter user id and password of HANA system. You will see the result as


Done!! You have successfully created your first XSJS service.

Continue reading:

1 comment: