In this guide, we'll show you how to gather user input during a phone call through the phone's keypad (using DTMF tones) in your Java Servlets application. By applying this technique, you can create interactive voice response (IVR) systems and other phone based interfaces for your users. The code snippets in this guide are written using Java and require the Java JDK 7 or higher. They also make use of the Twilio Java SDK.
Let's get started!
This guide assumes you have already set up your web application to receive incoming phone calls. If you still need to complete this step, check out this guide. It should walk you through the process of buying a Twilio number and configuring your app to receive incoming calls from it.
The <Gather> TwiML verb allows us to collect input from the user during a phone call. Gathering user input through the keypad is a core mechanism of Interactive Voice Response (IVR) systems where users can press "1" to connect to one menu of options and press "2" to reach another. These prompts can be accompanied by voice prompts to the caller, using the TwiML <Say> and <Play> verbs. In this example, we will prompt the user to enter a number to connect to a certain department within our little IVR system.
1import com.twilio.twiml.voice.Gather;2import com.twilio.twiml.voice.Redirect;3import com.twilio.twiml.voice.Say;4import com.twilio.twiml.TwiML;5import com.twilio.twiml.TwiMLException;6import com.twilio.twiml.VoiceResponse;78import javax.servlet.http.HttpServlet;9import javax.servlet.http.HttpServletRequest;10import javax.servlet.http.HttpServletResponse;11import java.io.IOException;1213public class VoiceServlet extends HttpServlet {1415public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {1617// Create a TwiML response and add our friendly message.18TwiML twiml = new VoiceResponse.Builder()19.gather(20new Gather.Builder()21.numDigits(1)22.say(new Say.Builder("For sales, press 1. For support, press 2.").build())23.build()24)25.redirect(new Redirect.Builder().url("/voice").build())26.build();2728response.setContentType("application/xml");29try {30response.getWriter().print(twiml.toXml());31} catch (TwiMLException e) {32throw new RuntimeException(e);33}34}35}
If the user doesn't enter any input after a configurable timeout, Twilio will continue processing the TwiML in the document to determine what should happen next in the call. When the end of the document is reached, Twilio will hang up the call. In the above example, we use the <Redirect> verb to have Twilio request the same URL again, repeating the prompt for the user
If a user were to enter input with the example above, the user would hear the same prompt over and over again regardless of what button you pressed. By default, if the user does enter input in the <Gather>, Twilio will send another HTTP request to the current webhook URL with a POST
parameter containing the Digits entered by the user. In the sample above, we weren't handling this input at all. Let's update that logic to also process user input if it is present.
1import com.twilio.twiml.*;23import javax.servlet.http.HttpServlet;4import javax.servlet.http.HttpServletRequest;5import javax.servlet.http.HttpServletResponse;6import java.io.IOException;78public class VoiceServlet extends HttpServlet {910public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {1112// Create a TwiML response and add our friendly message.13VoiceResponse.Builder builder = new VoiceResponse.Builder();1415String digits = request.getParameter("Digits");16if (digits != null) {17switch (digits) {18case "1":19builder.say(new Say.Builder("You selected sales. Good for you!").build());20break;21case "2":22builder.say(new Say.Builder("You need support. We will help!").build());23break;24default:25builder.say(new Say.Builder("Sorry, I don\'t understand that choice.").build());26appendGather(builder);27break;28}29} else {30appendGather(builder);31}3233response.setContentType("application/xml");34try {35response.getWriter().print(builder.build().toXml());36} catch (TwiMLException e) {37throw new RuntimeException(e);38}39}4041private static void appendGather(VoiceResponse.Builder builder) {42builder.gather(new Gather.Builder()43.numDigits(1)44.say(new Say.Builder("For sales, press 1. For support, press 2.").build())45.build()46)47.redirect(new Redirect.Builder().url("/voice").build());48}49}
You may want to have an entirely different endpoint in your application handle the processing of user input. This is possible using the "action" attribute of the <Gather> verb. Let's update our example to add a second endpoint that will be responsible for handling user input.
1import com.twilio.twiml.*;23import javax.servlet.http.HttpServlet;4import javax.servlet.http.HttpServletRequest;5import javax.servlet.http.HttpServletResponse;6import java.io.IOException;78public class VoiceServlet extends HttpServlet {910public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {1112// Create a TwiML response and add our friendly message.13TwiML twiml = new VoiceResponse.Builder()14.gather(new Gather.Builder()15.numDigits(1)16.action("/gather")17.say(new Say.Builder("For sales, press 1. For support, press 2.").build())18.build()19)20.redirect(new Redirect.Builder().url("/voice").build())21.build();2223response.setContentType("application/xml");24try {25response.getWriter().print(twiml.toXml());26} catch (TwiMLException e) {27throw new RuntimeException(e);28}29}30}
1import com.twilio.twiml.voice.Redirect;2import com.twilio.twiml.voice.Say;3import com.twilio.twiml.TwiMLException;4import com.twilio.twiml.VoiceResponse;56import javax.servlet.http.HttpServlet;7import javax.servlet.http.HttpServletRequest;8import javax.servlet.http.HttpServletResponse;9import java.io.IOException;1011public class GatherServlet extends HttpServlet {1213public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {1415// Create a TwiML response and add our friendly message.16VoiceResponse.Builder builder = new VoiceResponse.Builder();1718String digits = request.getParameter("Digits");19if (digits != null) {20switch (digits) {21case "1":22builder.say(new Say.Builder("You selected sales. Good for you!").build());23break;24case "2":25builder.say(new Say.Builder("You need support. We will help!").build());26break;27default:28builder.say(new Say.Builder("Sorry, I don\'t understand that choice.").build());29builder.redirect(new Redirect.Builder().url("/voice").build());30break;31}32} else {33builder.redirect(new Redirect.Builder().url("/voice").build());34}3536response.setContentType("application/xml");37try {38response.getWriter().print(builder.build().toXml());39} catch (TwiMLException e) {40throw new RuntimeException(e);41}42}43}
The action attribute takes a relative URL which would point to another route your server is capable of handling. Now, instead of conditional logic in a single route, we use actions and redirects to handle our call logic with separate code paths.
If you're building call center type applications in Java Servlets, you might enjoy stepping through full sample applications that implement a full IVR system.