Home

 

Creating a service using a servlet

We can create a service with a servlet, by writing the code to return a response in JSON format.

Note: For this example, we use a servlet and the JSON4J library to demonstrate a programmatic way to return information in JSON format.

To expose a servlet as a service, do these steps:

Right-click RAD75Web20Dojo and select New Æ Servlet.

In the Create Servlet dialog, enter the following items, and click Finish.

Java Package: itso.bank.servlet
Class Name: CustomerServlet

The CustomerServlet class opens in the editor. Use the code in C:\7672code\web20\CustomerServlet.java to complete the code.

Remove the constructor and the doPost method.
Complete the doGet method (Example | 9-5).

Example 19-5 Servlet doGet method

protected void doGet(......) throws ServletException, IOException {

response.setContentType("text/plain");

response.getWriter().write(getCustomers());

response.getWriter().flush();

response.getWriter().close();

}

Add the getCustomers method (Example | 9-6).

Example 19-6 Retrieving all customers and return a JSON object

private String getCustomers() {

JSONObject jSONObject = new JSONObject();

JSONArray jSONArray = new JSONArray();

try {

jSONObject.put("items", jSONArray);

CustomerManager customerManager = new CustomerManager();

List<Customer> customerList =

customerManager.getCustomerOrdered();

for (Customer customer : customerList) {

JSONObject obj = new JSONObject();

obj.put("ssn", customer.getSsn());

jSONArray.add(obj);

}

jSONObject.put("identifier", "ssn");

jSONObject.put("items", jSONArray);

} catch (Exception ex) {

ex.printStackTrace();

}

return jSONObject.toString();

}

Select Source Æ Organize Imports (or press Ctrl+Shift+O) to resolve the classes (com.ibm.json.java.JSONObject, java.util.List).

The new getCustomers method returns a response in JSON format to populate a combo box with a list of SSN.

Save and close the CustomerServlet.
ibm.com/redbooks